请稍候,加载中....

ssh远程命令执行

 

1. ssh远程免密登陆

ssh默认情况下登陆主机需要输入账户密码进行远程登陆,比如下图登陆远程192.168.3.40服务器时,需要输入登陆密码,

有的时候,比如在python程序中,需要在远程服务器上ssh后执行命令的时候,就需要免密登陆,免密登陆就是无需输入密码这个步骤,即可完成登陆

2. 如何实现远程免密登陆

免密登陆借助ssh密钥实现,生成本地主机的一对ssl密钥,将公钥发给远程主机

step1: 检查本地密钥:

luxp@luxpdeMacBook-Pro-2 ~ %  ls -al ~/.ssh/id_*.pub 

-rw-r--r--  1 luxp  staff  746  7 30  2018 /Users/luxp/.ssh/id_rsa.pub

使用ls -al ~/.ssh/id_*.pub 可以查看到本地是否已经存在密钥,可以使用已经存在的密钥

step2: 也可以生成一对新的ssl密钥:

luxp@luxpdeMacBook-Pro-2 ~ % ssh-keygen   

Generating public/private rsa key pair.

Enter file in which to save the key (/Users/luxp/.ssh/id_rsa): mykey

Enter passphrase (empty for no passphrase): 

Enter same passphrase again: 

Your identification has been saved in mykey.

Your public key has been saved in mykey.pub.

The key fingerprint is:

SHA256:ZggxQmT+ImxS2tAgu+UoDBlgU2x3KecIHUvf8r6MD1U luxp@luxpdeMacBook-Pro-2.local

The key's randomart image is:

+---[RSA 3072]----+

|*=B.+o. .        |

|oO.=.*o+.        |

|= * +.*o . E     |

|+X . o oo .      |

|B++ . . So       |

|+. .   oo        |

|       . .       |

|        + .      |

|       ..+       |

+----[SHA256]-----+

luxp@luxpdeMacBook-Pro-2 ~ % 

以上操作在当前目录生成:

Your identification has been saved in mykey.

Your public key has been saved in mykey.pub.

step3: 密钥生成后,将公钥传输到远程主机的.ssh配置下

luxp@luxpdeMacBook-Pro-2 ~ % ssh-copy-id -i mykey.pub   root@192.168.3.40

/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "mykey.pub"

/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed

/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys

root@192.168.3.40's password: 

 

Number of key(s) added:        1

 

Now try logging into the machine, with:   "ssh 'root@192.168.3.40'"

and check to make sure that only the key(s) you wanted were added.

 

luxp@luxpdeMacBook-Pro-2 ~ % 

以上操作,会将mykey.pub传到192.168.3.40主机

.ssh/authorized_keys 

如果没有ssh-copy-id命令,可以

cat  .mykey_pub | ssh remote_username@server_ip_address "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys"

传输完成后,接口免密登陆

ssh root@192.168.3.40

远程命令执行

ssh root@192.168.3.40  "ls -al"


Python学习手册-