Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Windows server remote command execution (PowerShell+WinRM)

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/02 Report--

Windows remote Management (WinRM) is a Microsoft implementation of the WS-Management protocol. This protocol is a firewall-friendly standard protocol based on simple object access Protocol (SOAP), which enables hardware and operating systems from different vendors to interoperate. The WS-Management protocol is developed by a group of hardware and software manufacturers as a common standard that can be used to remotely exchange management data with any computer device that implements the protocol.

To use PowerShell to remotely manage the server, enable WinRM on the remote server.

1. Knowledge reserve:

1. WinRM related operations

Enable the WinRM service:

Enable-PSRemoting-Force

Prevent the local computer from receiving remote commands (WinRM service will not be stopped):

Disable-psremoting-Force

View WinRM service snooping information:

Winrm enumerate winrm/config/Listener

WinRM2.0 default port 5985 (HTTP port) or 5986 (HTTPS port).

Delete WinRM HTTP snooping:

Winrm delete winrm/config/listener?Address=*+Transport=HTTP

Re-establish HTTP snooping:

Winrm create winrm/config/listener?Address=*+Transport=HTTP

WinRM service change listening port:

Set-item-force wsman:\ localhost\ listener\ listener*\ port 5985

View the configuration of WinRM:

Winrm get winrm/config

View port snooping status:

Netstat-nao | findstr "5985"

2. PowerShell script saving credential method

Using the Get-Credential command to interactively enter credentials (username + password), you can first save the credentials to a variable, such as:

$cred = get-credential

The object type name of $cred is: System.Management.Automation.PSCredential, where Password and UserName are its properties, so you can create a new object of that type. Note here that the Password type is SecureString,UserName and the type is String, so you need to convert the plaintext Password to a secure string, you can use the ConvertTo-SecureString command.

Example of a non-interactive credential code:

$account = "administrator" $password = '123456' $secpwd = convertto-securestring $password-asplaintext-force $cred = new-object System.Management.Automation.PSCredential-argumentlist $account,$secpwd

3 、 Invoke-Command

Invoke-Command runs commands on both local and remote computers and returns all output from the command, including errors. With a single Invoke-Command command, you can run commands on multiple computers. Some parameters are described as follows:

-Port

Specify the network port on the remote computer to use for this command. Specify a new port if the default listening port of WinRM is changed.

-ComputerName

Specify the computer on which to run this command. The default value is the local computer.

When you use the ComputerName parameter, Windows PowerShell creates a temporary connection that is used only to run the specified command and then closes. If a persistent connection is required, use the Session parameter.

Type the NETBIOS name, IP address, or fully qualified domain name of one or more computers in a comma-separated list. To specify the local computer, type the computer name, "localhost", or period (.).

To use the IP address in the value of the ComputerName parameter, the command must include the Credential parameter. In addition, the HTTPS transport must be configured for the computer, or the WinRM TrustedHosts address of the remote computer must be included in the IP list on the local computer.

-Session

Run this command in the specified Windows PowerShell session (PSSession).

A persistent connection to a remote computer can be established by creating a PSSession,Windows PowerShell.

-Credential

Specify the user account that is authorized to perform this operation. The default is the current user.

-command/-ScriptBlock

Specify the command to run. Enclose the command in curly braces ({}) to form a script block.

-FilePath

Runs the specified local script on one or more remote computers.

-AsJob

Run the command as a background job on the remote computer. Use this parameter to run commands that take a long time to complete.

When using AsJob, this command returns the object that represents the job, and then displays a command prompt. To manage jobs, use Job cmdlet. To get the job results, use Receive-Job.

-ThrottleLimit

Specifies the maximum number of concurrent connections that can be established to run this command. If you omit this parameter or enter a value of 0, the default value of 32 is used.

4 、 PSSession

PSSession is a Windows PowerShell session. Use PSSession when you need a continuous connection to a remote computer. PSSession related commands:

Enter-PSSession

Start an interactive session with the remote computer.

New-PSSession

Create a PSSession and return an object that represents PSSession. You can save the object in a variable.

Get-PSSession

Gets the PSSession created in the current session. Get-PSSession returns an object of the same type as the object returned by New-PSSession.

Remove-PSSession

Delete the PSSession and release the resources it is using.

Add the computer name to the TrustedHosts list

To add all computers to the list of trusted hosts, use the following command:

Set-item wsman:localhost\ client\ trustedhosts-Force-value *

You can also use the wildcard character (*) to add all computers in a specific domain to the list of trusted hosts.

For example, the following command adds all computers in the Fabrikam domain to the list of trusted hosts.

Set-item wsman:localhost\ client\ trustedhosts * .fabrikam.com

To add the IP address of a specific computer to the list of trusted hosts, use the following command format (IP supports the wildcard character *):

Set-item wsman:\ localhost\ Client\ TrustedHosts-value "[,]"

To view a list of trusted hosts, use the following command:

Get-item wsman:\ localhost\ Client\ TrustedHosts

Second, common scenarios of remote operation

Scenario 1: remote interactive session

This scenario is generally used to perform remote operations manually, enter commands, and view the results. The method is simple. The command to enter an interactive session is Enter-PSSession, and you can type Exit-PSSession or exit when you exit. During a remote interactive operation, the commands entered run on the remote computer as if they were entered and executed directly on the remote computer. The execution results of the variables and commands defined during are no longer available after exiting the interactive session.

Scenario 1 example: # user enters credentials (username + password) $cred=get-Credential# to establish a remote interactive session Enter-PSSession-computername 192.168.21.1-Credential $cred

Scenario 2: one-time execution of script blocks and script files

In this scenario, a temporary session is established between the local computer and the remote computer. Send the contents of the script block or script file to the remote computer for execution and send the results back to the local computer. This method is very efficient and is recommended by PowerShell to execute remote commands. This method is recommended unless you need to share data in a session.

Scenario 2 example, # user enters credentials (username + password) $cred=get-Credential# remote execution command invoke-command-computername 192.168.21.1-Credential $cred-command {dir invoke-command /} invoke-command-computername 192.168.21.1-Credential $cred-ScriptBlock {dir c:\} # remote execution script echo "dir c:\" > dirDriveC.ps1invoke-command-computername 192.168.21.1-Credential $cred-FilePath.\ dirDriveC.ps1

Example of scenario 2 (multiple remote hosts), # user enters credentials (username + password) $cred=get-Credential# batch executes the command invoke-command-computername 192.168.21.1192.168.21.4192.168.21.7-Credential $cred-ScriptBlock {dir c:\} # if the number of concurrent connections is set to 1 invoke-command-computername 192.168.21.1198.21.4192.168.21.7-Credential $cred-ThrottleLimit 1-ScriptBlock {dir c:\}

Scenario 3: script blocks and script files are executed in a naming session

1. Define a session: use the new-pssession command to define a session, such as $session1 = new-pssession-computername server1. (use the Credential parameter if necessary. )

2. Execute the script (or script file) remotely in the session: use the Invoke-Command command to execute the remote script, such as Invoke-Command-Session $session1-ScriptBlock {dir c:\} or Invoke-Command-Session $session1-FilePath.\ dirDriveC.ps1

3. Get the result: you can assign the execution result to variables, such as $sub = Invoke-Command-Session $session1-ScriptBlock {dir c:\} or $sub = Invoke-Command-Session $session1-FilePath.\ dirDriveC.ps1

Subsequent commands can be continued with reference to step 2 or 3, and all executed commands appear to be executed in the same context.

Scenario 3 example, # user enters credentials (username + password) $cred=get-Credential# to create PSSession and assigns the variable $session1 = new-pssession-computername 192.168.21.1-Credential $cred# remote execution command (persistent) Invoke-Command-Session $session1-ScriptBlock {$a = "hello world"} Invoke-Command-Session $session1-ScriptBlock {$a}

Scenario three examples (multiple remote hosts), # user input credentials (username + password) $cred=get-Credential# to create a PSSession for multiple remote hosts And assign the variable $session_many = new-pssession-computername 192.168.21.1192.168.21.4192.168.21.7-Credential $cred# to execute the command Invoke-Command-Session $session_many-ThrottleLimit 1-ScriptBlock {dir c:\} scenario for multiple remote hosts in batches (script mode), $account = "administrator" $password = '123456password # convert the password to SecureString$secpwd = convertto-securestring $password-asplaintext-force# New PSCredential object $cred = new-object System.Management.Automation.PSCredential-argumentlist $account The list of $secpwd# remote hosts is assigned to the variable [string []] $computername= "192.168.21.1", "192.168.21.4", "192.168.21.7" # create PSSession$session_many = new-pssession-computername $computername-Credential $cred# batch remote execution command Invoke-Command-Session$session_many-ThrottleLimit 1-ScriptBlock {dir c:\}

Reference:

Https://technet.microsoft.com/zh-cn/library/dd347578.aspx

Https://technet.microsoft.com/zh-cn/library/hh847839.aspx

Https://technet.microsoft.com/zh-cn/library/dd347642.aspx

Http://www.cnblogs.com/ceachy/archive/2013/02/20/PowerShell_Remoting.html

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report