find() 函数 找到就停止 不会继续往后找
实践1:堡垒机模式下的远程命令执行
堡垒机环境在一定程度上提升了运营安全级别,但同时也提高了日常运营成本,作为管理的中转设备,
任何针对业务服务器的管理请求都会经过此节点,比如SSH协议,首先运维人员在办公电脑通过SSH协
议登录堡垒机,再通过堡垒机SSH跳转到所有的业务服务器进行维护操作。
可以利用paramiko的invoke_shell机制来实现通过堡垒机实现服务器操作,原理是SSHClient.connect到
堡垒机后开启一个新的SSH会话(session),通过新的会话运行"ssh user@IP" 去实现远程执行命令的操
作。
import paramiko as pk
import os,sys,time
# 堡垒主机四要素
blj_ip = '10.1.8.10'
blj_user = 'root'
blj_pwd = '1'
prot = 22
# 业务服务器四要素
host = '10.1.8.20'
user = 'root'
pwd = '1'
# 准备
# 前置password字符串
passinfo = "'s password: " #单引号加转义符\ passinfo = '\'s password: '
# 日志记录
pk.util.log_to_file('system.log')
print(1)
# 创建SSHClient登录堡垒机
ssh = pk.SSHClient()
# 指定访问策略 允许未知主机访问
ssh.set_missing_host_key_policy(pk.AutoAddPolicy())
# 连接堡垒机
ssh.connect(hostname=blj_ip,username=blj_user,password=blj_pwd,port=prot)
print(2)
# 创建会话,开启远程命令调用
channel = ssh.invoke_shell()
# 会话超时
channel.settimeout(10)
# 缓存数据
buff = ''
# 回应数据
resp = ''
print(3)
# 在堡垒主机中启用ssh的session会话远程登录业务服务器
channel.send('ssh '+user+'@'+host+'\n')
# ssh登录提示判断,输出字符串尾部含有's password: 结尾时 退出循环
while not buff.endswith(passinfo):
try:
resp = channel.recv(9999).decode('utf-8')
except Exception as err:
print('ERR info:'+str(err)+'connnection time.')
channel.close()
ssh.close()
sys.exit()
# 正常回应消息
buff += resp
# 如果第一次登录会出现(yes/no)
if not buff.find('yes/no') == -1 :
channel.send('yes\n')
buff = ''
# 遇到password:需要发送密码
channel.send(pwd+'\n')
buff = ''
print(4)
# 输出字符串尾部有# 说明登录成功 退出循环
while not buff.endswith('# '):
resp = channel.recv(9999).decode('utf-8')
# 如果输入密码失效,要求重新输入密码
if not resp.find(passinfo) == -1:
print('ERR info: Password failed')
channel.close()
ssh.close()
sys.exit()
buff += resp
print(5)
# 验证通过 登录成功 发送操作指令
channel.send('mkdir /data\n')
buff = ''
try:
while buff.find('# ') == -1:
resp = channel.recv(9999).decode('utf8')
buff = resp
except Exception as err:
print('ERR info:'+str(err))
#打印回应信息
print(buff)
#资源关闭
channel.close()
ssh.close()
运行结果 代码中print1~5可以去掉 不去掉是为了测试那边有问题
C:\Users\......\远程执行命令.py
1
2
3
4
5
[root@localhost ~]#
进程已结束,退出代码为 0