This code use pexpect module of python to perform the operation.
[code language=”python”]
#v1.0 – to supply password and login
import sys
import pexpect
user = ‘user’
password = ‘password’
host = ‘host1.us.com’
command = ‘hostname ; echo $?’
def dossh(user, password, host, command):
child = pexpect.spawn(‘ssh %s@%s %s’ % (user,host,command),logfile=sys.stdout,timeout=None)
prompt = child.expect([‘password:’, r"yes/no",pexpect.EOF])
if prompt == 0:
child.sendline(password)
elif prompt == 1:
child.sendline("yes")
child.expect("password:", timeout=30)
child.sendline(password)
data = child.read()
print data
child.close()
dossh(user, password, host, command)
[/code]
Using the sys module this can be further enhanced to pass the arguments in argv[n].
Here logs will be written in stdout but it can be changed to any logfile.
Also this can be modified to perofrm scp operation or any othere complex command on remote server. Correct the indentation after copying the code.
or any other expected prompt can be added in the list and value can be passed as required.
Its enhanced here to handle passwordless authentication as well.
[code language=”python”]
#!/usr/bin/env python
#v1.1 – To handle both password and passwordless authentication
import sys
import pexpect
user = ‘user1’
password = ‘welcome1’
host = sys.argv[1]
command = ‘hostname; whoami; echo $?’
def dossh(user,password,host,command):
try:
child = pexpect.spawn("ssh -o ServerAliveInterval=100 -n %s@%s ‘%s’" % (user,host,command),logfile=sys.stdout,timeout=None)
i = child.expect([‘password:’, r’\(yes\/no\)’,r’.*[$#] ‘,pexpect.EOF])
if i == 0:
child.sendline(password)
elif i == 1:
child.sendline("yes")
ret1 = child.expect(["password:",pexpect.EOF])
if ret1 == 0:
child.sendline(password)
else:
pass
else:
pass
data = child.read()
print data
child.close()
return True
except Exception as error:
print error
return False
dossh(user, password, host, command)
[/code]