Paswd_key = '. *assword.* ' match password
Ssh_newkey = '. * (yes/no). * ' Match is sure you want to continue connecting (yes/no)
[Python]View Plaincopy
- #!/usr/bin/python2.7
- Import Pexpect
- Import OS, sys, getpass
- def ssh_command (user, host, password, command):
- Ssh_newkey = '. * (yes/no). * '
- Passwd_key = '. *assword.* '
- Child = Pexpect.spawn (' ssh-l%s%s '% (user, host, command))
- Child.logfile = Sys.stdout
- i = Child.expect ([Pexpect. TIMEOUT, Ssh_newkey, Passwd_key])
- if i = = 0: #timeout
- Print Child.before
- print "Error Time Out"
- Print Child.after
- return None
- if i = =1:
- Child.sendline (' yes ')
- i = Child.expect ([Pexpect. TIMEOUT, Passwd_key])
- 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):
- Passwd_key = '. *assword.* '
- if Os.path.isdir (filename):
- CmdLine = ' scp-r%s%[email protected]%s:%s '% (filename, user, IP, dst_path)
- Else:
- CmdLine = ' scp%s%[email protected]%s:%s '% (filename, user, IP, dst_path)
- Try:
- Child = Pexpect.spawn (cmdline)
- Child.expect (Passwd_key)
- Child.sendline (passwd)
- Child.expect (Pexpect. EOF)
- #child. Interact ()
- #child. Read ()
- #child. Expect (' $ ')
- print "uploading"
- except:
- print "Upload faild!"
- def main ():
- 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
- if __name__ = = "__main__":
- Main ()
Python pexpec to resolve SCP ssh