实现堡垒机模式下的远程命令执行

[root@node110 paramiko]# cat simple3.py 
#!/usr/bin/env python
import paramiko
import os,sys,time


hostname="192.168.2.121"
username="root"
password="123456"


blip="192.168.2.120"
bluser="root"
blpasswd="123456"


port=22
passinfo='\'s password: '
paramiko.util.log_to_file('syslogin.log')


ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=blip,username=bluser,password=blpasswd)


#new session
channel=ssh.invoke_shell()
channel.settimeout(10)


buff = ''
resp = ''
channel.send('ssh '+username+'@'+hostname+'\n')


while not buff.endswith(passinfo):
    try:
        resp = channel.recv(9999)
    except Exception,e:
        print 'Error info:%s connection time.' % (str(e))
        channel.close()
        ssh.close()
        sys.exit()
    buff += resp
    if not buff.find('yes/no')==-1:
        channel.send('yes\n')
buff=''


channel.send(password+'\n')


buff=''
while not buff.endswith('# '):
    resp = channel.recv(9999)
    if not resp.find(passinfo)==-1:
        print 'Error info: Authentication failed.'
        channel.close()
        ssh.close()
        sys.exit() 
    buff += resp


channel.send('ifconfig\n')
buff=''
try: 
    while buff.find('# ')==-1:
        resp = channel.recv(9999)
        buff += resp
except Exception, e:
    print "error info:"+str(e)


print buff
channel.close()
ssh.close()


结果:
[root@node110 paramiko]# python simple3.py 
ifconfig
docker0   Link encap:Ethernet  HWaddr 62:E1:7C:42:A3:D3  
          inet addr:172.17.42.1  Bcast:0.0.0.0  Mask:255.255.0.0
          inet6 addr: fe80::60e1:7cff:fe42:a3d3/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:6 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0 
          RX bytes:0 (0.0 b)  TX bytes:468 (468.0 b)


eth2      Link encap:Ethernet  HWaddr 00:0C:29:EF:E7:72  
          inet addr:192.168.2.121  Bcast:192.168.255.255  Mask:255.255.0.0
          inet6 addr: fe80::20c:29ff:feef:e772/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:555154 errors:0 dropped:0 overruns:0 frame:0
          TX packets:101 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000 
          RX bytes:33353001 (31.8 MiB)  TX bytes:18478 (18.0 KiB)



分割线
感谢打赏
江西数库信息技术有限公司
YWSOS.COM 平台代运维解决方案
 评论
 发表评论
姓   名:

Powered by AKCMS