简体   繁体   中英

Python ssh to a server having a username and password to login using subprocess only

There is text file called ip_addresses.txt containing 3 IP addresses:

192.x.x.x
192.x.x.x
192.x.x.x

I want to ssh to all of these servers and execute a shell command. Here is code snippet:

ip = open("ip_addresses.txt", "r")
data = ip.readlines()
for ips in data:
    ips = ips.strip("\n")
    ssh = subProcess.Popen(["ssh", "%s" % ips], stdin = subprocerss.PIPE, stdout= subprocess.PIPE, stderr =subprocess.PIPE)
ssh.stdin.write("ls -ltr")
result = ssh.stdout.readlines()
if result == []:
    error = ssh.stderr.readlines()
    print >>sys.stderr, "ERROR: %s" %error
else:
    print result

But to ssh make a ssh connection to these servers, I have to provide a username and password too, which are root and sam@123 . How can I provide these details as well and check a successful login to the servers.

Thanks

You have quite a few options. The two I can think of straight away:

  1. Setup a key-based authentication mechanism to avoid passwords (You'll have to put your public key on your server's authorized_keys file. Here's a howto .)
  2. Pexpect

If you do want to use Subprocess itself, have you tried ssh.stdin.write("password\\n") ?

use this :

def ssh(host, cmd, user, password, timeout=30, bg_run=False):                                                                                                 
    """SSH'es to a host using the supplied credentials and executes a command.                                                                                                 
    Throws an exception if the command doesn't return 0.                                                                                                                       
    bgrun: run command in the background"""                                                                                                                                    

    fname = tempfile.mktemp()                                                                                                                                                  
    fout = open(fname, 'w')                                                                                                                                                    

    options = '-q -oStrictHostKeyChecking=no -oUserKnownHostsFile=/dev/null -oPubkeyAuthentication=no'                                                                         
    if bg_run:                                                                                                                                                         
        options += ' -f'                                                                                                                                                       
    ssh_cmd = 'ssh %s@%s %s "%s"' % (user, host, options, cmd)                                                                                                                 
    child = pexpect.spawn(ssh_cmd, timeout=timeout)                                                                                                                            
    child.expect(['password: '])                                                                                                                                                                                                                                                                                               
    child.sendline(password)                                                                                                                                                   
    child.logfile = fout                                                                                                                                                       
    child.expect(pexpect.EOF)                                                                                                                                                  
    child.close()                                                                                                                                                              
    fout.close()                                                                                                                                                               

    fin = open(fname, 'r')                                                                                                                                                     
    stdout = fin.read()                                                                                                                                                        
    fin.close()                                                                                                                                                                

    if 0 != child.exitstatus:                                                                                                                                                  
        raise Exception(stdout)                                                                                                                                                

    return stdout

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM