📜 ⬆️ ⬇️

Manage Windows computers from the Linux console

Here the task of managing a computer on Windows from Linux was considered. Solved using winexe.

The similar problem of remote installation of software, checking the status, remote shutdown / reboot of a large group of Windows computers (classrooms) below is solved using freeSSHd - ssh server for Windows.

The site is only the latest version of freeSSHd - 1.3.1. It works for me unstable (sometimes the service drops). The previous version - 1.2.4 - works fine from XP to Win8.1, although there is a small exploit - but it seems like nothing except how to fill up the FreeSSHDService service, so you can close your eyes to this. Just in case, put this version here (size - 782456)

Run the installer, in the process we change the installation path ("C: \ Program Files (x86) \ FreeSSHD") to C: \ bin \ FreeSSHD - it is easier to find it on systems with different architecture and the config will be the same everywhere. (C: \ bin must first be created.)
')
Then everything is by default - at the end of the FreeSSHDService service starts. It can be configured by clicking the tray icon, but it is easier to copy the finished settings to the C: \ bin \ FreeSSHD \ FreeSSHDService.ini settings file and restart the service.
Example FreeSSHDService.ini:
[Telnet server] TelnetListenAddress=0.0.0.0 TelnetListenPort=23 TelnetMaxConnections=0 TelnetTimeout=0 TelnetBanner= TelnetCMD=C:\Windows\system32\cmd.exe TelnetRun=0 TelnetNewConsole=1 [SSH server] SSHListenAddress=0.0.0.0 SSHListenPort=22 SSHMaxConnections=0 SSHTimeout=0 SSHBanner= SSHCMD=C:\Windows\system32\cmd.exe SSHRun=1 SSHNewConsole=1 SSHCiphers=0 SSHMACs=65535 SSHPasswordAuth=0 SSHPublickeyAuth=0 SSHPublickeyPath=C:\bin\freeSSHd\ RSAKeyPath=C:\bin\freeSSHd\RSAKey.cfg DSAKeyPath=C:\bin\freeSSHd\DSAKey.cfg [SSH tunneling] SSHLocalTunnel=0 SSHLocalTunnelOnly=0 SSHRemoteTunnel=0 SSHRemoteTunnelOnly=0 [SFTP] SFTPHomePath=$HOME\ [Access filtering] HostRestrictions= HostRestrictionsAllow=0 [Logging] LogEvents=0 LogFilePath=C:\bin\freeSSHd\freesshd.log LogResolveIP=0 [Automatic updates] UpdateCheckOnStartup=0 UpdateDontPrompt=0 UpdateShowMessages=1 UpdateLastMessageID=0 [Users] UserCount=1 [User0] Name=admin Auth=2 Password=000000000000000000000000000000000000000000 Domain= Shell=1 SFTP=1 Tunnel=1 

Now it is necessary to complete the announced user admin - create the file C: \ bin \ FreeSSHD \ admin and write the public key there.

Either use the existing id_dsa.pub, or in the Linux console, type
 /# ssh-keygen -t dsa 

and get a pair of keys - id_dsa and id_dsa.pub
On Windows, copy id_dsa.pub to the C: \ bin \ FreeSSHD directory and rename it to C: \ bin \ FreeSSHD \ admin

Restarting FreeSSHDService service:
 net stop FreeSSHDService & net start FreeSSHDService 


On Linux, we check the connection (listing the root C: \):
 /# ssh -2q -i <my_key_files_path>/id_dsa -ladmin -oStrictHostKeyChecking=no -oUserKnownHostsFile=/dev/null <Win_Host_IP> "cmd /c dir c:\\" 

If the host rejects the connection (on win7-win8 probably), configure the Firewall in the "Network Control Center ...":
Windows Firewall -> network troubleshooting -> incoming connections -> something else -> review -> C: \ bin \ FreeSSHD \ FreeSSHDService.exe

If everything worked out, copy the directory C: \ bin \ FreeSSHD \ to all the other computers - then during the installation FreeSSHD will ask far fewer questions and the already configured will start. Of course, you can implement all this and configure the Firewall through Group Policy, but I did not bother with this - all the computers were cloned from one successful image.

Now you can execute any (almost) command on any computer.
For example, reboot:
 /# ssh -2q -i <my_key_files_path>/id_dsa -ladmin -oStrictHostKeyChecking=no -oUserKnownHostsFile=/dev/null <Win_Host_IP> "cmd /c shutdown /r /t 1" 


Installation 1s (silent):
 /# ssh -2q -i <my_key_files_path>/id_dsa -ladmin -oStrictHostKeyChecking=no -oUserKnownHostsFile=/dev/null \ <Win_Host_IP> "cmd /c start \\\\<Server_IP>\\buh\\1Ccurrent\\setup /s" 

Since the access is console, then when you try to start the program from the GUI, you must use the start from the new window - “start”. Although silent installation of 1C and does not require a GUI.

When there are many computers, the launch of commands in turn is ineffective, it is necessary to fork sessions.
A Python demo program that polls computers in the 192.168.0.210-192.168.0.220 range and writes their names to the /tmp/rexec.log log. Those who do not answer are marked as NA, and hung sessions -? T:
 #!/usr/bin/python # -*- coding: utf-8 -*- log = '/tmp/rexec.log' host_range = range(210,220) ip_first_3 = '192.168.0' my_key = '/root/.ssh/id_dsa' my_cmd = 'hostname' #  #my_cmd = 'shutdown /s /t 10' # #my_cmd = r'\\\\srv1\\shar1\\mycmd.bat' #       import os,sys,time,subprocess from datetime import datetime try: cmd = '/usr/bin/ssh -2q -oBatchMode=yes -oStrictHostKeyChecking=no -oUserKnownHostsFile=/dev/null -i%s -ladmin %s.%%d "cmd /c %s " ' % (my_key,ip_first_3,my_cmd) procs,out,err = [],[],[] for x in host_range: xcmd = cmd % x procs.append([x,subprocess.Popen(xcmd,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,shell=True,bufsize=4096,executable='/bin/bash')]) for i in range(0,20): #20   1  stop = True for proc in procs: # print i, proc[0] if proc[0] == 0: continue try: res = proc[1].poll() if res == None: stop = False continue if res == 0: out.append("%d:%s" % (proc[0],proc[1].stdout.read().splitlines()[0])) #  1   ! else: err.append("%d:NA" % proc[0]) except: err.append("%d:EX" % proc[0]) proc[0]=0 if stop: break time.sleep(1) if not stop: #   for proc in procs: if proc[0] != 0: proc[1].terminate() err.append("%d:?T" % proc[0]) s = "%s|%s" % ('; '.join(out),'; '.join(err)) except: s = "!!! Error" print s with open(log, "ab") as fp: fp.write("--- %s cmd=%s\n" % (datetime.strftime(datetime.now(), "%Y.%m.%d %H:%M:%S"),my_cmd)) fp.write(" Result: %s\n" % s) 

(The source program was a CGI script, hence the minimalism of the output)

Difficult and long teams are better arranged in a batch file and placed in an accessible network path. On a Samba resource, you must give the file permissions to execute and arrange line ends in the style of Windows.

Source: https://habr.com/ru/post/259469/


All Articles