ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
## 前言 一般情况下,我们需要ssh连接远程服务器,然后手动输入密码才能实现登录,但我们在做某些远程部署命令或者就是连接服务器时不希望每次都去查阅去输入服务器密码,尤其你密码很多的时候。那么本文就给大家介绍下免输入密码的福利哦。 作为前提,大家都知道ssh连接并不是git连接项目时专属的,它是连接服务器的一种通用协议,在github,gitlab的时候你也是通过吧自己的公钥放在自己的ssh中实现的。(win系统有crt软件,可以提供终端界面以及记录密码账号功能,所以如果你有那个软件可以忽略本教程) ## 服务器ssh的设置 ### 生成公钥 生成公钥与 私钥的步骤与git中的相关教程完全一致.这里需要注意的是你对应的账号设置是root@10.0.0.36 ~~~ //检测是否生成配置了ssh key ssh -T git@github.com //如果已经配置好 Hi csnikey! You've successfully authenticated, but GitHub does not provide shell access. // 如果没有配置好 Permission denied (publickey). fatal: The remote end hung up unexpectedly // 生成ssh key,如果你已经安装了git cd ~/.ssh ssh-keygen -t rsa -C you@Email.com //遇到 提示一路 回车,遇到有Y 输入Y(其中针对不同的代码平台,需要增加不用的ssh文件) //添加ssh key(如果提示你权限不够,需要添加这个key,并同时注意必须切换到文档根目录下,~/.ssh下面) ssh-add id_rsa //若出现: Could not open a connection to your authenticationagent. ssh-agent bash //在使用 ssh-add id_rsa //登录github.com --AccountSetting--ssh 点击Add 将id_rsa.pub 文件中的 内容添加进去 ~~~ ### 公钥移动到远程服务器 #### 方式1 :代码部署 ~~~ //传到远程也需要:账号@host ssh-copy-id -i 36_id_rsa.pub root@10.0.0.36 //已经部署的 /usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "36_id_rsa.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: WARNING: All keys were skipped because they already exist on the remote system. (if you think this is a mistake, you may want to use -f option) //没有部署情况 /usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "36_id_rsa.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@10.0.0.36's password: //部署成功提示: Number of key(s) added: 1 Now try logging into the machine, with: "ssh 'root@10.0.0.36'" and check to make sure that only the key(s) you wanted were added. ~~~ #### 方式2:远程编辑 找到远程目录/root/.ssh/authorized_keys vm或者文件编辑,将本地的36_id_rsa.pub添加到key即可 ### 意外情况 如果提示你没有权限修改,比如permission denied.需要你切换到对应的账户目录,然后设置权限最高。 ~~~ chmod 777 /root/.ssh/authorized_keys //提出chmod没有权限 chmod: 更改"authorized_keys" 的权限: 不允许的操作 //进一步设置 chattr chattr -i /etc/fstab ~~~ **说明:** chattr可以防止关键文件被修改,在linux下,有些配置文件是不允许任何人包括root修改的,为了防止被误删除或修改,可以设定该文件的"不可修改位(immutable)"。 ~~~ //不可以修改文件 chattr +i /etc/fstab //如果需要修改文件则: chattr -i /etc/fstab ~~~ ## 其他常识 ~~~ #连接某服务器 ssh xxx@host # 断开连接 exit logout ~~~