windows 脚本_paramiko, pywinrm实现windows/linux脚本调用

"""
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"}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用Python的paramiko实现Windows上与Linux机器之间的文件传输。具体步骤如下: 1. 安装paramiko库 可以使用pip命令安装paramiko库,命令为: ``` pip install paramiko ``` 2. 编写脚本Windows上编写一个Python脚本,使用paramiko库连接到Linux机器,然后执行文件同步命令。 以下是示例代码: ```python import os import paramiko import time # 定义本地和远程目录 local_path = '/path/to/local/dir' remote_path = '/path/to/remote/dir' # 定义Linux机器的IP地址和登录信息 ip_list = ['192.168.1.100', '192.168.1.101'] username = 'username' password = 'password' # 创建SSH客户端 client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # 定义同步函数 def sync_files(): # 遍历Linux机器列表 for ip in ip_list: client.connect(ip, username=username, password=password) # 获取本地目录下的文件列表 files = os.listdir(local_path) # 遍历本地文件列表,将文件同步到远程目录 for file in files: local_file_path = os.path.join(local_path, file) remote_file_path = os.path.join(remote_path, file) # 判断是否为目录,如果是则递归同步 if os.path.isdir(local_file_path): # 创建远程目录 stdin, stdout, stderr = client.exec_command('mkdir -p ' + remote_file_path) stderr_lines = stderr.readlines() if len(stderr_lines) > 0: print(stderr_lines) # 递归同步子目录 sync_files(local_file_path, remote_file_path) else: # 同步文件 sftp = client.open_sftp() sftp.put(local_file_path, remote_file_path) sftp.close() # 同步文件,每隔5分钟同步一次 while True: sync_files() time.sleep(300) ``` 上述代码中,定义了本地目录和远程目录的路径,以及Linux机器的IP地址列表和登录信息。然后通过paramiko库创建SSH客户端,遍历Linux机器列表,连接到每台Linux机器。接着定义了一个同步函数,用于将本地目录下的文件同步到远程目录。在while循环中调用同步函数,每隔5分钟同步一次。 3. 运行脚本Windows上运行脚本即可实现定时同步文件和文件夹至多台Linux机器。可以使用Windows的计划任务功能,或者使用第三方定时任务软件,如cron等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值