Windows10 子系统 Ubuntu 设置开机启动【ssh】_skume的博客-CSDN博客_ubuntu win10 开机启动
由于 Ubuntu 18.4 已经废弃了 initd 管理模块,改用 systemd,而作为 Windows的子系统是不支持 systemd,显然得另辟蹊径。
为了实现 ssh 服务能开机启动,现在只能通过自定义 shell 脚本达到目的。
! /bin/sh
startup ssh service.
service ssh start
将文件保存在
/etc/sshd
并为该文件添加可执行权限,头部的 #! /bin/sh 为该文件的打开方式。
chmod +x /etc/sshd
但目前的困难是怎么在电脑开机后去执行这个文件?也就是让 Ubuntu 去执行这个命令呢?
经搜索发现,ubuntu 可以运行命令行,在 cmd 中输入 ubuntu —help 可以看到 run 这个选项
C:\Users\win>ubuntu —help
Launches or configures a Linux distribution.
Usage:
Launches the user’s default shell in the user’s home directory.
install [--root]
Install the distribuiton and do not launch the shell when complete.
--root
Do not create a user account and leave the default user set to root.
run <command line>
Run the provided command line in the current working directory. If no
command line is provided, the default shell is launched.
config [setting [value]]
Configure settings for this distribution.
Settings:
--default-user <username>
Sets the default user to <username>. This must be an existing user.
help
Print usage information.
C:\Users\win>
现在基本可以解决问题了,写一个批处理的事情。(别慌,其实也就第 7 行代码是核心)
@echo off
title sshd 启动服务
echo.
echo 启动 ssh 服务…
timeout /t 2 >nul
echo.
ubuntu run /etc/sshd
echo.
echo.
timeout /t 5 /NOBREAK
exit
将以上内容保存为 sshd.cmd,并且将该文件移动到系统的启动目录。(打开运行窗口,执行 shell:startup 可以一键打开)
C:\Users\win\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
重启电脑,发现还是无法用 ssh 登录,重新运行脚本,发现问题,没有权限。
普通用户想要执行 root 命令,必须通过 sudo 授权,但面临的问题是需要密码验证,唯二办法就是处理 /etc/sudoers
切换到 root 或者直接执行
sudo sh -c ‘echo %sudo ALL=NOPASSWD: /etc/sshd >>/etc/sudoers’
完成后,普通用户就可以直接运行 sudo /etc/sshd
别忘了上面的脚本也改动以下
@echo off
title sshd 启动服务
echo.
echo 启动 ssh 服务…
timeout /t 2 >nul
echo.
ubuntu run sudo /etc/sshd
echo.
echo.
timeout /t 5 /NOBREAK
exit
打开任务管理器就可以看到刚刚添加的启动项和状态。不放心的可以先运行下脚本,看看效果。