如何自动化终端命令?
我对这样做感到厌倦。
ssh me@somehost.com
input my password
sudo su - someuser
input my password
cd /some/working/directory
<run some commands>
有没有办法让这个过程自动化?我需要一个特殊的命令行工具吗?或者一个命令行模拟器?我能不能通过编程的方式让命令行运行到某个阶段,然后手动输入命令?
如果能用Python编写,那就更棒了,感觉更有黑客的味道。
补充说明:下面的回答都集中在“完全自动化”这个部分,但我觉得最难的就是我上面强调的那部分。这里有另一个例子,看看我能不能抓住要点。
ssh me@somehost.com
<get a shell because keys are setup>
sudo su - user_that_deploys_the_app
<input password, because we don't want to give passwordless sudo to developers>
cd env; source bin/activate
cd /path/where/ur/app/is/staging
<edit some files, restart the server, edit some more, check the logs, etc.>
exit the term
7 个回答
1
我不太确定你具体在问什么,但你可能是在问如何通过公钥让SSH工作而不需要输入密码。大致的思路是你需要生成一对SSH密钥:
ssh-keygen -t rsa
这会生成两个文件,分别是 id_rsa
和 id_rsa.pub
。你需要把 id_rsa.pub
的内容添加到目标用户的 ~/.ssh/authorized_keys
文件中。这样,从那以后,使用SSH连接时就不需要再输入凭据了。在你的例子中,这个过程只需要做一次:
只需一次
# On your source machine
ssh-keygen -t rsa
cat ~/.ssh/id_rsa.pub
# Copy this to clip board
# On somehost.com
su - someuser
# edit ~/.ssh/authorized_keys and paste what you had copied from previous step
从现在开始,你只需运行
ssh someuser@somehost.com "sh -c 'cd /some/dir; command.sh'"
就不会再被要求输入凭据了。
1
fabric是个不错的选择,正如其他人所提到的。另外,还有一个叫pexpect的工具,可能更符合你的需求。
2
关于ssh和认证的部分,你可以通过设置无密码认证来使用密钥。这样你就可以简单地使用ssh
和一个bash脚本来自动执行一系列命令。
你可以在这里使用Python,但如果你要执行一系列的shell命令,使用shell脚本可能更合适,因为它们就是专门用来做这个的。
另外,你可以看看Fabric来满足你的自动化需求。它是基于Python的,你的“配方”是用Python写的。