如何通过 ssh 在我的网络中使用本地主机关闭远程主机?

DeL*_*LiK 8 ssh shutdown openssh wakeonlan

问题很简单。
我必须使用什么脚本来通过 ssh 关闭网络中的计算机。

通常我会去命令行和:

ssh desktop

delik@desktop's password: 

delik@desktop:~$ sudo shutdown -P 0
Run Code Online (Sandbox Code Playgroud)

为了开机,我创建了一个文件并写道:

wakeonlan xx:xx:xx:xx:xx:xx
Run Code Online (Sandbox Code Playgroud)

并给它可执行位

这种打开电源的方式只需要双击即可。我能做同样的关闭吗?

DeL*_*LiK 10

对于以下内容,我假设您要使用的用户remote-host与您使用的相同local-host

为了做你想做的事,你必须首先授权你local-hostremote-host没有密码的情况下连接到你。为此,您必须(如此处所述):

  1. 安装ssh

    sudo apt-get install ssh
    
    Run Code Online (Sandbox Code Playgroud)
  2. 通过在您的以下命令中输入此命令,使用ssh-key-genon创建公钥和私钥:local-hostlocalhost

    ssh-keygen
    
    Run Code Online (Sandbox Code Playgroud)

    您应该将生成的密钥保存在:

    /home/yourusername/.ssh/id_rsa
    
    Run Code Online (Sandbox Code Playgroud)

    按两次 Enter 将密码留空。

    Your identification has been saved in /home/yourusername/.ssh/id_rsa.
    Your public key has been saved in /home/yourusername/.ssh/id_rsa.pub.
    The key fingerprint is:
    XX:XX:XX:xX:XX:xX:XX:XX:XX:XX:XX:XX:XX:XX yourusername@local-host
    
    Run Code Online (Sandbox Code Playgroud)
  3. 将公钥复制到remote-hostusing ssh-copy-id

    yourusername@local-host$ ssh-copy-id -i ~/.ssh/id_rsa.pub remote-host
    yourusername@remote-host's password:
    
    Now try logging into the machine, with:
    
    ssh remote-host
    
    Run Code Online (Sandbox Code Playgroud)

    并检查.ssh/authorized_keys以确保我们没有添加您不期望的额外密钥。

    注意:ssh-copy-id将键附加到remote-host/home/yourusername/.ssh/authorized_key.

  4. 登录remote-host无需输入密码:

    ssh remote-host
    yourusername@remote-host:~$
    
    Run Code Online (Sandbox Code Playgroud)

    remote-host无需密码即可访问。成功!

现在您必须能够在没有密码的情况执行sudo shutdown -P 0。您可以通过修改做到这一点/etc/sudoersremote-hostvisudo。这样,用户yourusername可以在shutdown不询问密码的情况下执行命令。

  1. 登录remote-host

    ssh remote.host
    
    Run Code Online (Sandbox Code Playgroud)
  2. 跑:

    sudo visudo
    
    Run Code Online (Sandbox Code Playgroud)

    通过运行visudo,您可以/etc/sudoers安全地进行编辑。

  3. 将此行添加到文件中:

    yourusername ALL = NOPASSWD: /sbin/shutdown
    
    Run Code Online (Sandbox Code Playgroud)
  4. 这样做之后,回到你的local-host,创建一个新的空文件并粘贴这一行,修改remote-host的名称:

    ssh remote.host sudo shutdown -P 0
    
    Run Code Online (Sandbox Code Playgroud)
  5. 保存并关闭文件,right-click在其上转到其属性权限,并勾选将此文件作为程序执行

脚本完成!