"""
paramiko, pywinrm实现windows/linux脚本调用
"""
import paramiko
import winrm
import json
class ServerByPara(object):
def __init__(self, cmd, host, user, password, system_choice):
self.cmd = cmd
self.client = paramiko.SSHClient()
self.host = host
self.user = user
self.pwd = password
self.system_choice = system_choice
def exec_linux_cmd(self):
data_init = ''
self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.client.connect(hostname=self.host, username=self.user, password=self.pwd)
stdin, stdout, stderr = self.client.exec_command(self.cmd, get_pty=True)
if stderr.readlines():
exec_tag = 1
for data in stdout.readlines():
data_init += data
else:
exec_tag = 0
for data in stdout.readlines():
data_init += data
return json.dumps({
"exec_tag": exec_tag,
"data": data_init,
}, ensure_ascii=False)
def exec_win_cmd(self):
data_init = ""
s = winrm.Session(self.host, auth=(self.user, self.pwd))
ret = s.run_cmd(self.cmd)
if ret.std_err.decode():
exec_tag = 1
for data in ret.std_err.decode().split("rn"):
data_init += data
else:
exec_tag = 0
for data in ret.std_out.decode().split("rn"):
data_init += data
return json.dumps({
"exec_tag": exec_tag,
"data": data_init,
}, ensure_ascii=False)
def run(self):
if self.system_choice == "Linux":
result = self.exec_linux_cmd()
else:
result = self.exec_win_cmd()
print(result)
with open(r"script_info.txt", "w") as f:
f.write(result)
# if __name__ == '__main__':
# server_obj = ServerByPara(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4])
# server_obj = ServerByPara(r"C:UsersaDesktoptest.bat", "192.168.12.149", "a",
# "password", "Windows")
# server_obj = ServerByPara(r"/root/Desktop/test.sh >> log.txt", "192.168.109.132", "root",
# "password", "Linux")
# server_obj.run()
工具:1.针对Linux系统,使用paramiko模块,通过ssh协议,不需要在服务器上安装任何服务; 2.针对Windows系统,使用pywinrm模块,通过winrm服务,需要在windows上开始winrm服务(默认是关闭的);
.Windows系统
2.1 在以管理员身份运行的powershell中执行命令,winrm quickconfig或winrm qc 查看winrm是否开启成功,如果提示未开始,输入enter执行提示操作开始winrm;
2.2 将网络设置为专用网络;
2.3 执行一下两个命令,允许其他机器链接:
winrm set winrm/config/service/auth @{Basic="true"}
winrm set winrm/config/service @{AllowUnencrypted="true"}