上一篇文章提到利用Python连接Windows Server,具体参照利用Python自动化发布(连接服务器实现文件的上传/下载)
因为项目服务器用的是window server,所以在连接服务器这里废了好大劲,最后还是借鉴了运维小哥的方法:利用cygwin开启ssh服务,cygwin自带的命令行工具可以把Windows当Linux来玩
Cygwin是一个能把Windows 当成Linux来玩的工具,引用官网的一句话:
Cygwin (64-bit) is a collection of tools which provide a Linux look and feel environment for Windows.
简单来说,我们配置完Cygwin,就能用Linux命令操作Windows了
话不多说 先连接到服务器上,下载Cygwin,官网的下载地址在这,如果打不开可以试试第三方的网站
1.下载完直接打开安装程序,如下图,无脑下一步
2.选择install from internet
3.选择下安装路径
4.选择包安装路径
5.选择Use Internet Explorer Proxy Settings
6.选择 http://cygwin.mirror.constant.com ,可能会出现网络错误,多选几次就行
7.到了选择安装包步骤,输入ssh,安装ssh相关的插件(默认是没有SSH 的,要手动选择. 不知道选哪个就都选中)
8.配置一下cygwin的环境变量
右击我的电脑 , 属性> 高级> 环境变量
在系统变量下 点击新建, 添加变量名 CYGWIN , 变量值 ntsec
在系统变量下, 编辑Path, 添加 ;c:\cygwin64\bin
9.配置SSHD服务 (此步骤需上网查找一下详细解释)
运行 C:\cygwin64\Cygwin.bat或终端
在窗口中输入
ssh-host-config
*** Query: Should privilege separation be used? <yes/no>: yes
*** Query: New local account 'sshd'? <yes/no>: yes
*** Query: Do you want to install sshd as a service?
*** Query: <Say "no" if it is already installed as a service> <yes/no>: yes
*** Query: Enter the value of CYGWIN for the deamon: [] binmode ntsec
*** Query: Do you want to use a different name? (yes/no) yes/no
如果用相同的名字 cyg_server, 输入no.
*** Query: Create new privileged user account 'cyg_server'? (yes/no) yes
*** Query: Please enter the password:
*** Query: Renter:
如果选择不同的名字, 输入 yes.
*** Query: Enter the new user name: cyg_server1
*** Query: Reenter: cyg_server1
*** Query: Create new privileged user account 'cyg_server1'? (yes/no) yes
*** Query: Please enter the password:
*** Query: Reenter:
配置成功,你会看到下面消息:
Host configuration finished. Have fun!
10.启动服务,找到cygsshd,右击启动
11.到此整个过程基本完成,为了防止windowsServer服务器重启之后,cygwin服务停止,还可以再添加一个开机自启动
打开系统启动路径,C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp,将想要设置成开机自启的程序快捷方式添加到其中即可,或者删除其中快捷方式即可取消开机自启。如下图:
12.这样就搞定了,我们可以来测试一下连接
这边是通过iterm自带的ssh命令连接,Windows的话有xshell等ssh工具,这个就自行选择吧
具体命令:ssh root@hostname
root:你连接服务器的用户名
hostname:你的服务器IP
回车输出: Enter passphrase for key '/Users/arthurw/.ssh/id_rsa':
直接回车跳过,输出:root@hostname's password:
输入用户名密码,回车就连接上了
cd / 进入cygwin的系统盘
cd cygdrive 就能进入Windows的系统盘了,这样就测试通过了
写在最后:
费这么大劲就是为了给Windows server开启ssh的服务,可以通过ssh工具直接连接到服务器(不然通过堡垒机就特别麻烦,一些自动化的工具根本没法发挥作用),比如Jenkins的一些持续集成任务就可以操作了,还有你自己写的一些小工具。
这样一来,我们写的python脚本,就可以对服务器进行操作了。