#!/usr/bin/python2.7
import pexpect
import os, getpass
def ssh_command(user, host, password, command):
ssh_newkey = 'Are you sure you want to continue connecting'
child = pexpect.spawn('ssh -l %s %s %s' %(user, host, command))
i = child.expect([pexpect.TIMEOUT, ssh_newkey, 'password: '])
if i == 0: #timeout
print child.before
print "Error time out"
print child.after
return None
if i ==1 :
child.sendline('yes')
child.expect('password: ')
i = child.expect([pexpect.TIMEOUT, 'password: '])
if i == 0:
print child.before
print 'time out ERROR'
print child.after
return None
child.sendline(password)
return child
def scp2(ip, user, passwd, dst_path, filename):
if os.path.isdir(filename):
cmdline = 'scp -r %s %s@%s:%s' % (filename, user, ip, dst_path)
else:
cmdline = 'scp %s %s@%s:%s' % (filename, user, ip, dst_path)
try:
child = pexpect.spawn(cmdline)
child.expect('password:')
child.sendline(passwd)
child.expect(pexpect.EOF)
#child.interact()
#child.read()
#child.expect('$')
print "uploading"
except:
print "upload faild!"
def main1():
host = raw_input('Hostname:')
user = raw_input('User:')
password = getpass.getpass()
command = raw_input('Command:')
child = ssh_command(user, host, password, command)
child.expect(pexpect.EOF)
print child.before
def main():
pass
if __name__ == "__main__":
pass
Python pexpec 解决scp ssh
最新推荐文章于 2022-02-14 23:35:27 发布