你能帮我纠正我的python脚本吗?以下脚本使用python pexpect模块执行scp到目标主机。如果我得到Permission denied异常,我想处理一个包含密码列表的本地数组变量,然后继续使用scp。
local_pass = ["test123","welcome1","Welcome1"]
def file_copy(user,host,password,logfile,local_file):
print "Connecting to %s as %s" % (host,user)
local_file_copy = local_file
remote_file = os.path.basename(local_file)
print "Performing scp %s %s@%s:/tmp/%s" % (local_file,user,host,remote_file)
p=pexpect.spawn("scp %s %s@%s:/tmp/%s" % (local_file,user,host,remote_file))
p.timeout=10
i=p.expect([ssh_newkey,'assword:'],p.timeout)
print "setting log file %s" % (logfile)
fout=file(logfile,'w')
p.logfile=fout
counter=0
if i == 0:
print "yes to continue connecting"
p.sendline("yes");
i=p.expect([ssh_newkey,'assword:'],p.timeout)
if i == 1:
try:
print "entering ssh password %s" % (password)
output=p.sendline(password)
sys.exit(1)
except:
while(counter < 3):
print "Permission Denied...\n"
#p.expect(['Permission denied, please try again.\r\n'],p.timeout)
p.expect(['assword:'],p.timeout)
p.sendline("%s" %(local_pass[counter]))
print "Attempting to relogin....\n"
print "LOCALPASSWORD : --> %s\n" %(local_pass[counter])
counter+=1;
j=p.expect("]","#","$")
if j in range(4):
break;
print "returning expect handle"
p.expect(pexpect.EOF)
print "Script file has been copied to target host"
谢谢,
答案 0 :(得分:1)
嗯,你的代码看起来很复杂且难以理解。为什么你要解决已解决的问题?
我建议将openssh-wrapper模块与ssh键结合使用。这让生活变得轻松:
您的代码将如下所示:
from openssh_wrapper import SSHConnection
def upload(local_file, remote_file):
conn = SSHConnection('your-server.com', login='username', port=22, identity_file='~/.ssh/id_rsa')
response = conn.scp(local_file, target='/tmp/', mode='0655', owner='username')
print response
如果您希望每次都输入密码,也可以使用ssh键保留该部分。 此代码未经测试,但无论如何都应该有效..