使用winrm远程连接windows server2019并批量执行powershell命令

1.AD域服务器操作

AD域服务器 快速配置开启winrm服务,如果没开启服务,则会报错:

2020-05-05 15:51:27,945  ERROR  localAD.py  40  the specified credentials were rejected by the server

这里是AD域服务器需要配置的命令:

winrm quickconfig
winrm e winrm/config/listener
winrm set winrm/config/service/auth @{Basic="true"}
winrm set winrm/config/service @{AllowUnencrypted="true"}
winrm get winrm/config

部分截图:
在这里插入图片描述

2.winrm使用演示

2.1 安装pywinrm 0.4.1

这里有一个坑,pip install的是pywinrm,但是python代码导包的时候写的应该是import winrm,特别注意一下,在这里纠结了好一会。

2.2示例代码

import logging
import winrm

# 日志设置
LOG_FORMAT = "%(asctime)s  %(levelname)s  %(filename)s  %(lineno)d  %(message)s"
logging.basicConfig(filename='localAD.log', level=logging.INFO, format=LOG_FORMAT)

# 本地AD域
LDAP_IP_LOCAL = '192.168.255.222'        # LDAP本地服务器IP
LDAP_ADMIN_USER_LOCAL = 'CN=Administrator,CN=Users,DC=bilibili,DC=com'      # LDAP本地服务器管理员账户
LDAP_ADMIN_PWD_LOCAL = 'QQqq#123'        # LDAP本地服务器管理员密码


# powershell命令,用于打开/关闭OU是否被删除的权限
cmd_list_enable_del = ["Import-Module ActiveDirectory",
                       "Get-ADOrganizationalUnit -filter * -Properties ProtectedFromAccidentalDeletion | where {"
                       "$_.ProtectedFromAccidentalDeletion -eq $true} | ft",
                       "Get-ADOrganizationalUnit -filter * -Properties ProtectedFromAccidentalDeletion | where {"
                       "$_.ProtectedFromAccidentalDeletion -eq $true} |Set-ADOrganizationalUnit "
                       "-ProtectedFromAccidentalDeletion $false"]
cmd_list_disable_del = ["Import-Module ActiveDirectory",
                        "Get-ADOrganizationalUnit -filter * -Properties ProtectedFromAccidentalDeletion | where {"
                        "$_.ProtectedFromAccidentalDeletion -eq $false} | ft",
                        "Get-ADOrganizationalUnit -filter * -Properties ProtectedFromAccidentalDeletion | where {"
                        "$_.ProtectedFromAccidentalDeletion -eq $false} |Set-ADOrganizationalUnit "
                        "-ProtectedFromAccidentalDeletion $true"]


def enable_del_ou_right(ip, user, pwd, cmd_l):
    try:
        win = winrm.Session('http://' + ip + ':5985/wsman', auth=(user, pwd))
        for cmd in cmd_l:
            ret = win.run_ps(cmd)
            if ret.status_code == 0:  # 调用成功
                logging.info('执行命令【' + cmd + '】成功')
            else:
                return False
        return True
    except Exception as e:
        logging.error(e)


if __name__ == '__main__':
    # 调用ps脚本,开启OU删除权限
    # modify_right_res = enable_del_ou_right(LDAP_IP_LOCAL, 'administrator', LDAP_ADMIN_PWD_LOCAL, cmd_list_enable_del)

    # 关闭OU删除权限
    enable_del_ou_right(LDAP_IP_LOCAL, 'administrator', LDAP_ADMIN_PWD_LOCAL, cmd_list_disable_del)

说明:关闭了OU的删除权限后,AD域中OU右键,对象中,可以看到所有OU都设置好了防止对象被意外删除:
在这里插入图片描述
下面是日志中记载的:

2020-05-05 15:54:41,783  INFO  localAD.py  35  执行命令【Import-Module ActiveDirectory】成功
2020-05-05 15:54:44,319  INFO  localAD.py  35  执行命令【Get-ADOrganizationalUnit -filter * -Properties ProtectedFromAccidentalDeletion | where {$_.ProtectedFromAccidentalDeletion -eq $false} | ft】成功
2020-05-05 15:54:45,461  INFO  localAD.py  35  执行命令【Get-ADOrganizationalUnit -filter * -Properties ProtectedFromAccidentalDeletion | where {$_.ProtectedFromAccidentalDeletion -eq $false} |Set-ADOrganizationalUnit -ProtectedFromAccidentalDeletion $true】成功

以上测试代码是远程连接修改AD域的,可以通过下面更简单的代码,看下出了什么问题

import winrm

# 虚机服务器server 2019
IP_LOCAL = '192.168.255.223'        # 服务器IP
PWD_LOCAL = 'QQqq#123'              # 服务器管理员密码

# 测试的命令
CMD = [
    'mkdir win_test_file'
]


def run_cmd(ip, user, pwd, cmd_list):
    try:
        win = winrm.Session('http://' + ip + ':5985/wsman', auth=(user, pwd))
        for cmd in cmd_list:
            ret = win.run_ps(cmd)
            if ret.status_code == 0:  # 调用成功
                print(cmd)
            else:
                return False
        return True
    except Exception as e:
        print(e)


if __name__ == '__main__':
    # 测试命令执行
    run_cmd(IP_LOCAL, 'administrator', PWD_LOCAL, CMD)

如果报
the specified credentials were rejected by the server
账户密码有问题,其他问题 在核查中

我有两台server2019虚拟机192.168.255.222那台可能是账号密码填写错误,
192.168.255.223这台测试是ok的,可以在用户文件夹中生成一个文件夹
在这里插入图片描述
执行截图
在这里插入图片描述

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
在Java中使用WinRM技术需要使用WinRM4j库,下面是一个简单的示例代码: ```java import com.github.kubesys.winrm.WinRMFactory; import com.github.kubesys.winrm.WinRmTool; import com.github.kubesys.winrm.exception.WinRMException; import com.github.kubesys.winrm.ssl.TrustAllCerts; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.net.URI; import java.nio.charset.StandardCharsets; public class WinRMExample { public static void main(String[] args) throws IOException, WinRMException { String hostname = "remote-server.example.com"; String username = "remote-user"; String password = "remote-password"; String endpoint = String.format("https://%s:5986/wsman", hostname); WinRmTool.Builder builder = WinRMFactory.builder(endpoint, username, password); builder.setAuthenticationScheme(WinRmTool.AuthenticationScheme.NTLM); builder.setHttpsNoVerification(); builder.setListener(new WinRmTool.Listener() { @Override public void onStdout(String message) { System.out.println("STDOUT: " + message); } @Override public void onStderr(String message) { System.err.println("STDERR: " + message); } }); WinRmTool tool = builder.build(); tool.executeCommand("ipconfig"); // 上传文件 String remoteFile = "C:\\test\\file.txt"; String localFile = "/path/to/local/file.txt"; byte[] content = "Hello, World!".getBytes(StandardCharsets.UTF_8); try (FileOutputStream out = new FileOutputStream(new File(localFile))) { out.write(content); } tool.copyToRemote(localFile, remoteFile); // 下载文件 byte[] remoteContent = tool.copyFromRemote(remoteFile); String downloadedFile = "/path/to/downloaded/file.txt"; try (FileOutputStream out = new FileOutputStream(new File(downloadedFile))) { out.write(remoteContent); } } } ``` 在上面的示例代码中,我们使用WinRMFactory创建WinRmTool对象,并设置了远程服务器的连接参数、身份验证方式、HTTPS证书验证方式和监听器。然后我们调用executeCommand方法执行命令,并使用copyToRemote和copyFromRemote方法上传和下载文件。需要注意的是,如果远程服务器没有安装WinRM服务,需要先安装WinRM服务并启用WinRM服务。
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值