freme / sshpt

Automatically exported from code.google.com/p/sshpt
0 stars 0 forks source link

sshpt with keys #15

Open GoogleCodeExporter opened 9 years ago

GoogleCodeExporter commented 9 years ago
What steps will reproduce the problem?
1. run sshpt with a provided username against a host that requires no password 
(key-based authentication)

What is the expected output?
sshpt connects and executes desired commands without prompting for a password

What do you see instead?
password prompt

What version of the product are you using? On what operating system?
[N840F7LKS53SU2K:35033355] : </home/35033355>

$ sshpt --version
1.2.0
[N840F7LKS53SU2K:35033355] : </home/35033355>

$

Please provide any additional information below.
user keys and configuration housed under ~/.ssh. public keys have been 
installed to target system, but sshpt requests password, indicating that the 
software is ignoring key-based authentication

Original issue reported on code.google.com by kmhuntly on 17 Sep 2014 at 7:26

GoogleCodeExporter commented 9 years ago
here is the fix for this issue. 
I will also attach the full sshpt.py 

Index: sshpt.py
===================================================================
--- sshpt.py    (revision 41)
+++ sshpt.py    (working copy)
@@ -163,6 +163,7 @@
                 host = queueObj['host']
                 username = queueObj['username']
                 password = queueObj['password']
+                key_file = queueObj['key_file']
                 timeout = queueObj['timeout']
                 commands = queueObj['commands']
                 local_filepath = queueObj['local_filepath']
@@ -177,6 +178,7 @@
                     host,
                     username,
                     password,
+                    key_file,
                     timeout,
                     commands,
                     local_filepath,
@@ -229,12 +231,13 @@
             t.quit()
     return True

-def queueSSHConnection(ssh_connect_queue, host, username, password, timeout, 
commands, local_filepath, remote_filepath, execute, remove, sudo, run_as, port):
+def queueSSHConnection(ssh_connect_queue, host, username, password, key_file, 
timeout, commands, local_filepath, remote_filepath, execute, remove, sudo, 
run_as, port):
     """Add files to the SSH Queue (ssh_connect_queue)"""
     queueObj = {}
     queueObj['host'] = host
     queueObj['username'] = username
     queueObj['password'] = password
+    queueObj['key_file'] = key_file
     queueObj['timeout'] = timeout
     queueObj['commands'] = commands
     queueObj['local_filepath'] = local_filepath
@@ -247,14 +250,18 @@
     ssh_connect_queue.put(queueObj)
     return True

-def paramikoConnect(host, username, password, timeout, port=22):
+def paramikoConnect(host, username, password, key_file, timeout, port=22):
     """Connects to 'host' and returns a Paramiko transport object to use in further communications"""
     # Uncomment this line to turn on Paramiko debugging (good for troubleshooting why some servers report connection failures)
     #paramiko.util.log_to_file('paramiko.log')
     ssh = paramiko.SSHClient()
+    keyfile=os.path.expanduser('~')+'/.ssh/id_rsa'
     try:
         ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
-        ssh.connect(host, port=port, username=username, password=password, 
timeout=timeout)
+        if key_file:
+            ssh.connect(host, port=port, username=username, password=None, 
key_filename=keyfile, timeout=timeout)
+        else:
+            ssh.connect(host, port=port, username=username, password=password, 
timeout=timeout)
     except Exception, detail:
         # Connecting failed (for whatever reason)
         ssh = str(detail)
@@ -293,6 +300,7 @@
         host,
         username,
         password,
+        key_file,
         timeout=30, # Connection timeout
         commands=False, # Either False for no commnads or a list
         local_filepath=False, # Local path of the file to SFTP
@@ -312,7 +320,7 @@

     if host != "":
         try:
-            ssh = paramikoConnect(host, username, password, timeout, port=port)
+            ssh = paramikoConnect(host, username, password, key_file, timeout, 
port=port)
             if type(ssh) == type(""): # If ssh is a string that means the connection failed and 'ssh' is the details as to why
                 connection_result = False
                 command_output = ssh
@@ -358,6 +366,7 @@
         hostlist, # List - Hosts to connect to
         username,
         password,
+        key_file, # if login by ssh key instead password
         max_threads=10, # Maximum number of simultaneous connection attempts
         timeout=30, # Connection timeout
         commands=False, # List - Commands to execute on hosts (if False nothing will be executed)
@@ -390,7 +399,7 @@
     while len(hostlist) != 0: # Only add items to the ssh_connect_queue if there are available threads to take them.
         for host in hostlist:
             if ssh_connect_queue.qsize() <= max_threads:
-                queueSSHConnection(ssh_connect_queue, host, username, 
password, timeout, commands, local_filepath, remote_filepath, execute, remove, 
sudo, run_as, port)
+                queueSSHConnection(ssh_connect_queue, host, username, 
password, key_file, timeout, commands, local_filepath, remote_filepath, 
execute, remove, sudo, run_as, port)
                 hostlist.remove(host)
         sleep(1)
     ssh_connect_queue.join() # Wait until all jobs are done before exiting
@@ -419,9 +428,11 @@
     parser.add_option("-T", "--timeout", dest="timeout", default=30, help="Timeout (in seconds) before giving up on an SSH connection (default: 30)", metavar="<seconds>")
     parser.add_option("-s", "--sudo", action="store_true", dest="sudo", default=False, help="Use sudo to execute the command (default: as root).")
     parser.add_option("-U", "--sudouser", dest="run_as", default="root", help="Run the command (via sudo) as this user.", metavar="<username>")
+    parser.add_option("-k", "--keyfile", dest="key_file", default=None, 
help="SSH key file for passwordless login. This override --dk option", 
metavar="<file>")
+    parser.add_option("--dk", dest="default_key", action="store_true", 
default=False, help="use default ~/id_rsa key for passwordless login")

     (options, args) = parser.parse_args()
-
+    
     # Check to make sure we were passed at least one command line argument
     try:
         sys.argv[1]
@@ -451,6 +462,8 @@
     run_as = options.run_as
     verbose = options.verbose
     outfile = options.outfile
+    key_file = options.key_file
+    default_key = options.default_key

     if options.hostfile == None and not options.stdin:
         print "Error: You must supply a file (-f <file>) containing the host list to check "
@@ -487,12 +500,19 @@
         username, password = credentials.split(":")
         password = password.rstrip('\n') # Get rid of trailing newline

-    # Get the username and password to use when checking hosts
-    if username == None:
-        username = raw_input('Username: ')
-    if password == None:
-        password = getpass.getpass('Password: ')
-
+    #use ssh key to login
+    if key_file or default_key:
+        if not key_file:
+            key_file=os.path.expanduser('~')+'/.ssh/id_rsa'
+            
+    #need password for sudo even you have key            
+    if sudo or not key_file:
+        # Get the username and password to use when checking hosts
+        if username == None:
+            username = raw_input('Username: ')
+        if password == None:
+            password = getpass.getpass('Password: ')
+            
     hostlist_list = []

     try: # This wierd little sequence of loops allows us to hit control-C in the middle of program execution and get immediate results
@@ -499,7 +519,7 @@
         for host in hostlist.split("\n"): # Turn the hostlist into an actual list
             if host != "":
                 hostlist_list.append(host)
-        output_queue = sshpt(hostlist_list, username, password, max_threads, 
timeout, commands, local_filepath, remote_filepath, execute, remove, sudo, 
run_as, verbose, outfile, port=port)
+        output_queue = sshpt(hostlist_list, username, password, key_file, 
max_threads, timeout, commands, local_filepath, remote_filepath, execute, 
remove, sudo, run_as, verbose, outfile, port=port)
         output_queue.join() # Just to be safe we wait for the OutputThread to finish before moving on
     except KeyboardInterrupt:
         print 'caught KeyboardInterrupt, exiting...'

Original comment by rui.va...@gmail.com on 8 Oct 2014 at 6:44

Attachments:

GoogleCodeExporter commented 9 years ago
svn.diff also attached

Original comment by rui.va...@gmail.com on 8 Oct 2014 at 6:47

Attachments: