`
斌强-朱
  • 浏览: 48679 次
社区版块
存档分类
最新评论

Python pexpec 解决scp ssh

 
阅读更多


#!/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

		


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics