0

你能帮我纠正我的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"

谢谢,

4

1 回答 1

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 密钥保留该部分。此代码未经测试,但无论如何应该可以工作..

于 2013-08-13T13:07:05.013 回答