-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsshpass.py
executable file
·68 lines (53 loc) · 2.18 KB
/
sshpass.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#!/usr/bin/env python
''' Automate SSH logins when you're force to authenticate with a password. '''
import getpass
import optparse
import os
import sys
import pexpect
def gettermsize():
''' horrible non-portable hack to get the terminal size to transmit
to the child process spawned by pexpect '''
(rows, cols) = os.popen("stty size").read().split() # works on Mac OS X, YMMV
rows = int(rows)
cols = int(cols)
return (rows, cols)
def ssh(username, password, host, port=22, args = []):
''' Automate sending password when the server has public key auth disabled '''
print>>sys.stderr, "Connecting to %s@%s" % (username, host)
cmd = "/usr/bin/ssh -p%d %s@%s %s" % (port, username, host, ' '.join(args))
child = pexpect.spawn(cmd)
(rows, cols) = gettermsize()
child.setwinsize(rows, cols) # set the child to the size of the user's term
# handle the host acceptance and password crap.
i = -1
try:
i = child.expect(['Are you sure you want to continue connecting (yes/no)?', 'assword:'])
except:
print>>sys.stderr, 'Connection Failed, please check manually.'
return
if i == 0:
# accept the host
print>>sys.stderr, "New server, accept the host..."
child.sendline('yes')
child.expect('assword:')
print>>sys.stderr, "Sending password"
child.sendline(password)
# give control to the human.
child.interact()
if __name__=='__main__':
parser = optparse.OptionParser(usage="ssh.py [options] <username@>host")
parser.add_option("-k", "--keychainservice", dest="keychainservice", help="Keychain service name to store password under",
default="ssh_py_default")
parser.add_option("-p", "--port", dest="port", help="SSH port", default=22)
(opts, args) = parser.parse_args()
if len(args) != 1:
parser.print_usage()
sys.exit(1)
host_str = args[0]
if host_str.find("@") != -1:
(username, host) = host_str.split("@")
else:
username = os.getlogin() # default to username on the current host.
host = host_str
ssh(username, host, port=int(opts.port), keychainservice=opts.keychainservice)