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:
authorized_keys
file. Here's a howto .)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.