使用Bash脚本自动插入密码

时间:2015-05-21 20:09:05

标签: linux bash ubuntu ssh

我正在尝试自动化我的强制部署,只是想了解更多信息,我正在尝试在复制ssh密钥时自动插入机器的密码但是它仍然提示我每次都输入密码而且我是不知道为什么,也许它在提示之前发送密钥我不确定..

#!/bin/bash
apt-get update --force-yes
apt-get install software-properties-common -y --force-yes
apt-add-repository ppa:ansible/ansible -y --force-yes
apt-get update -y --force-yes
apt-get install ansible -y --force-yes
ssh-keygen -t rsa -N "" -f ~/.ssh/id_rsa 
ssh-copy-id root@0.0.0.0
send("mypass{enter}")

2 个答案:

答案 0 :(得分:3)

你可以使用expect,或者你知道python,你可以使用简单模块Pexpect:

#!/usr/bin/expect

set timeout 20

set ip [lindex $argv 0]

set user [lindex $argv 1]

set password [lindex $argv 2]

spawn ssh "$user\@$ip"

expect "Password:"

send "$password\r";

interact

最好的选择是将服务器配置为允许带密钥身份验证的ssh。

答案 1 :(得分:1)

如果可以提供帮助,您希望避免将密码放在任何类型的脚本中 - 您可以。 sshrsync等等都是通过公钥/私钥身份验证进行远程操作的全部内容。用它。除非您需要 rsa 加密,否则请使用 dsa

如何?你走在正确的轨道上。我们假设您在localhost,并希望更新/管理remotehost。 ansible docs说了什么?

  

与远程机器通话时,Ansible by   默认假设您使用SSH密钥。

如何设置SSH密钥?

简单。您需要在localhost上生成公开/私有密钥对,然后您将公钥转移到remotehost并将其附加到~/.ssh/authorized_keys {1}}文件。生成密钥对是一个命令(默认长度很好):

ssh-keygen -t dsa

默认情况下会在localhost中的~/.ssh/上创建以下内容:

-rw------- 1 youruser yourgroup 668 Jun 13  2008 id_dsa
-rw-r--r-- 1 youruser yourgroup 603 Jun 13  2008 id_dsa.pub

注意私钥 0600上的权限必须为id_dsa

将公开密钥转移到remotehost

rsync -uav ~/.ssh/id_dsa.pub remotehost:~/.ssh/id_dsa-localhost.pub

注意:按惯例,最好在remotehost上为公钥指定一个唯一名称,以避免无意中覆盖公众 - 另一位主持人的钥匙。 (即 - 将id_dsa.pub转移为id_dsa-localhost.pub)现在,您需要做的就是将公钥附加到authorized_keys文件中:

ssh remotehost "cat ~/.ssh/id_dsa-localhost.pub >> ~/.ssh/authorized_keys"

现在使用您的私钥从localhost remotehost 安全登录:

ssh remotehost

这就是它的全部内容。

我需要将文件传输为root,现在是

除了所有关于不执行此操作的正常警示尾声之外......您还有两个选择:为root创建另一个公钥/私钥对;或者,如果您是唯一的管理员/用户并且这是您的方框,则只需suroot并将/home/you/.ssh/id_dsa/home/you/.ssh/id_dsa.pub复制到/root/.ssh localhost

然后在remotehost(再次,您的方框),copy /home/you/.ssh/id_dsa-localhost.pub/root/.ssh/id_dsa-localhost.pub,然后将/root/.ssh/id_dsa-localhost.pub追加到/root/.ssh/authorized_keys(您必须检查/更新复制到owner:group的所有文件的root:root,并确保权限正确。)

注意:虽然sshd默认允许root登录,但有些发行版不会。您必须确保PermitRootLogin中的No未设置为/etc/ssh/sshd_config

那应该是它。如果有任何问题,请尝试使用ssh ssh -vv登录,您将获得诊断问题所需的所有信息。