1
1
#!/usr/bin/env python
3
"""This runs 'ls -l' on a remote host using SSH. At the prompts enter hostname,
6
$Id: sshls.py 489 2007-11-28 23:40:34Z noah $
3
'''This runs 'ls -l' on a remote host using SSH.
4
At the prompts enter hostname, username, and password.
8
This license is approved by the OSI and FSF as GPL-compatible.
9
http://opensource.org/licenses/isc-license.txt
11
Copyright (c) 2012, Noah Spurrier <noah@noah.org>
12
PERMISSION TO USE, COPY, MODIFY, AND/OR DISTRIBUTE THIS SOFTWARE FOR ANY
13
PURPOSE WITH OR WITHOUT FEE IS HEREBY GRANTED, PROVIDED THAT THE ABOVE
14
COPYRIGHT NOTICE AND THIS PERMISSION NOTICE APPEAR IN ALL COPIES.
15
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
16
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
17
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
18
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
19
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
20
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
21
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
25
from __future__ import print_function
27
from __future__ import absolute_import
12
39
def ssh_command (user, host, password, command):
14
"""This runs a command on the remote host. This could also be done with the
15
pxssh class, but this demonstrates what that class does at a simpler level.
16
This returns a pexpect.spawn object. This handles the case when you try to
17
connect to a new host and ssh asks you if you want to accept the public key
18
fingerprint and continue connecting. """
41
'''This runs a command on the remote host. This could also be done with the
42
pxssh class, but this demonstrates what that class does at a simpler level.
43
This returns a pexpect.spawn object. This handles the case when you try to
44
connect to a new host and ssh asks you if you want to accept the public key
45
fingerprint and continue connecting. '''
20
47
ssh_newkey = 'Are you sure you want to continue connecting'
21
48
child = pexpect.spawn('ssh -l %s %s %s'%(user, host, command))
22
49
i = child.expect([pexpect.TIMEOUT, ssh_newkey, 'password: '])
23
50
if i == 0: # Timeout
25
print 'SSH could not login. Here is what SSH said:'
26
print child.before, child.after
52
print('SSH could not login. Here is what SSH said:')
53
print(child.before, child.after)
28
55
if i == 1: # SSH does not have the public key. Just accept it.
29
56
child.sendline ('yes')
30
57
child.expect ('password: ')
31
58
i = child.expect([pexpect.TIMEOUT, 'password: '])
32
59
if i == 0: # Timeout
34
print 'SSH could not login. Here is what SSH said:'
35
print child.before, child.after
61
print('SSH could not login. Here is what SSH said:')
62
print(child.before, child.after)
37
64
child.sendline(password)