1.#!/usr/bin/python
2.#-*-
coding: UTF-8 -*-
3.
4.import
pexpect
5.import
os,os.path
6.import
stat
7.import
getpass
8.import
sys
9.import
getopt
10.import
socket
11.from
ConfigParser import ConfigParser
12.#import
subprocess
13.
14.def
usage():
15.print '\nUsage: ssh.py hostname'
16.sys.exit(0)
17.
18.#定义用户名和密码文件
19.def
load_config():
20.cfg_path = os.path.join(os.environ["HOME"],
".ssh.cfg")
21.cfg_temp = '''[connects]
22.user
=
23.id_rsa
=
24.'''
25.if not os.path.exists(cfg_path):
26.open(cfg_path, 'w').write(cfg_temp)
27.#
os.chmod(cfg_path, stat.S_IREAD)
28.cfg = ConfigParser()
29.cfg.read(cfg_path)
30.user = cfg.get('connects', 'user')
31.id_rsa = cfg.get('connects', 'id_rsa', 'True')
32.return (user,id_rsa)
33.
34.def
ssh_login (user, host, id_rsa):
35.ssh_newkey = 'Are you sure you want to continue connecting'
36.try:
37.child = pexpect.spawn('ssh -l %s %s '%(user,
host))
38.child.expect([pexpect.TIMEOUT, ssh_newkey,
'password: ', "id_rsa': "])
39.child.sendline(id_rsa)
40.#预知chr(26)的含义,请查看ASCII码对照表,字符一列.
41.child.interact(chr(26))
42.print "\n"
43.except:
44.print "interact error"
45.sys.exit(0)
46.
47.def
main ():
48.if len(sys.argv) == 1:
49.load_config()
50.usage()
51.
52.# load file
53.user,id_rsa = load_config()
54.
55.if user == '':
56.usage()
57.elif id_rsa == '':
58.usage()
59.else:
60.pass
61.#host = raw_input('hostname: ')
62.host = sys.argv[1]
63.#
print host
64.# use `ping` to check if the host is available now
65.#用ping的方式测试主机是否存在
66.try:
67.sock = socket.socket(socket.AF_INET,
socket.SOCK_STREAM)
68.sock.settimeout(3)
69.sock.connect((host, 22))
70.sock.close()
71.except:
72.print 'ping: unknown host %s' % (host)
73.sys.exit(0)
74.# ssh
75.ssh_login(user, host, id_rsa)
76.
77.if
__name__ == '__main__':
78.try:
79.main()
80.except Exception, e:
81.print str(e)
82.os._exit(1)