Managing Windows computers from the Linux console

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

    A similar task of remotely installing software, checking status, remotely shutting down / rebooting a large group of Windows computers (training classes) is solved below using freeSSHd , an ssh server for Windows.

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

    We launch the installer, in the process we change the installation path (“C: \ Program Files (x86) \ FreeSSHD”) to C: \ bin \ FreeSSHD - it’s easier to find it on systems with different architectures and the config will be the same everywhere. (C: \ bin must first be created.)

    Then everything is by default - at the end, the FreeSSHDService service starts. You can configure it by clicking the tray icon, but it’s easier to copy the finished settings to the settings file C: \ bin \ FreeSSHD \ FreeSSHDService.ini 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 we need to re-register the declared user admin - create the file C: \ bin \ FreeSSHD \ admin and write the public key there.

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

    and we get a key pair - 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

    Restart the FreeSSHDService service:
    net stop FreeSSHDService & net start FreeSSHDService


    On Linux, test the connection (listing the root of C: \):
    /# ssh -2q -i /id_dsa -ladmin -oStrictHostKeyChecking=no -oUserKnownHostsFile=/dev/null  "cmd /c dir c:\\"

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

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

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


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

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

    When there are a lot of computers, running commands in turn is inefficient; you need to fork the session.
    A demo program in Python that polls computers in the range 192.168.0.210-192.168.0.220 and writes their names to the /tmp/rexec.log log. Non-responders are marked as NA, and hanging sessions are? 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 original program was a CGI script, hence the minimal output). It is

    better to format complex and long commands as a batch file and place them in an accessible network path. On the Samba resource, you must give the file permission to execute and draw up the line ends in the style of Windows.

    Also popular now: