123456789101112131415161718192021222324252627282930313233343536373839404142434445 |
- import tempfile, pexpect
-
- def scp(src_name, dest_name, host, user, password, timeout=30, bg_run=False):
- """SSH'es to a host using the supplied credentials and executes a command.
- Throws an exception if the command doesn't return 0.
- bgrun: run command in the background"""
-
- fname = tempfile.mktemp()
- fout = open(fname, 'w')
-
- options = '-q -oStrictHostKeyChecking=no -oUserKnownHostsFile=/dev/null -oPubkeyAuthentication=no'
- if bg_run:
- options += ' -f'
- scp_cmd = 'scp %s %s@%s:%s' % (src_name, user, host, dest_name)
- child = pexpect.spawn(scp_cmd, timeout=timeout, encoding='UTF-8')
- child.expect(['password: '])
- child.sendline(password)
- child.logfile = fout
-
- child.expect(pexpect.EOF)
-
-
- # We expect any of these three patterns...
- #i = child.expect (['Permission denied', 'Terminal type', '[#\$] '])
- #if i==0:
- # print('Permission denied on host. Can\'t login')
- # child.kill(0)
- #elif i==1:
- # print('Login OK... need to send terminal type.')
- # child.sendline('vt100')
- # child.expect('[#\$] ')
- #elif i==2:
- # print('Login OK.')
- # print('Shell command prompt', child.after)
-
- child.close()
- fout.close()
-
- fin = open(fname, 'r')
- stdout = fin.read()
- fin.close()
-
- if 0 != child.exitstatus:
- raise Exception(stdout)
- return stdout
|