Sending a password over SSH or SCP with subprocess.Popen

后端 未结 6 1291
-上瘾入骨i
-上瘾入骨i 2020-12-01 17:13

I\'m trying to run an scp (secure copy) command using subprocess.Popen. The login requires that I send a password:

from subprocess import Popen         


        
6条回答
  •  无人及你
    2020-12-01 17:23

    Here is my scp function based on pexpect. It can handle wildcards (i.e. multiple file transfer), in addition to the password. To handle multiple file transfer (i.e. wildcards), we need to issue a command via a shell. Refer to pexpect FAQ.

    import pexpect
    
    def scp(src,user2,host2,tgt,pwd,opts='',timeout=30):
        ''' Performs the scp command. Transfers file(s) from local host to remote host '''
        cmd = f'''/bin/bash -c "scp {opts} {src} {user2}@{host2}:{tgt}"'''
        print("Executing the following cmd:",cmd,sep='\n')
    
        tmpFl = '/tmp/scp.log'
        fp = open(tmpFl,'wb')
        childP = pexpect.spawn(cmd,timeout=timeout)
        try:
            childP.sendline(cmd)
            childP.expect([f"{user2}@{host2}'s password:"])
            childP.sendline(pwd)
            childP.logfile = fp
            childP.expect(pexpect.EOF)
            childP.close()
            fp.close()
    
            fp = open(tmpFl,'r')
            stdout = fp.read()
            fp.close()
    
            if childP.exitstatus != 0:
                raise Exception(stdout)
        except KeyboardInterrupt:
            childP.close()
            fp.close()
            return
    
        print(stdout)
    

    It can be used this way:

    params = {
        'src': '/home/src/*.txt',
        'user2': 'userName',
        'host2': '192.168.1.300',
        'tgt': '/home/userName/',
        'pwd': myPwd(),
        'opts': '',
    }
    
    scp(**params)
    

提交回复
热议问题