linux ssh跳板机 记录会话,【ssh】通过跳板机自动登录目标服务器

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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值