在一些情况下需要在命令行交互式输入一些命令,像ssh root@xxx 或 git clone xxx
[root@one ~]# git clone http://gitlab.test.net/Yogur/for_test.git
Cloning into 'for_test'...
Username for 'http://gitlab.test.net':
Password for 'http://gitlab.test.net':
fatal: Authentication failed for 'http://gitlab.test.net/Yogur/for_test.git/'
如何在脚本实现git clone 并输入用户名密码呢
安装expect
yum -y install expect
脚本
cat test.sh
#!/bin/bash
expect -c "
spawn $1 #$1为要执行的命令
expect {
"*Username*:" {send $2
; exp_continue} #当匹配到Username时输入$2 回车
"*Password*:" {send $3
} #当匹配到Password时输入$2 回车
}
expect eof
"
执行脚本效果
[root@one Yogur]# bash test "git clone http://gitlab.test.net/Yogur/for_test.git" Yogur Yogur@333!
spawn git clone http://gitlab.test.net/Yogur/for_test.git
Cloning into 'for_test'...
Username for 'http://gitlab.test.net': Yogur
Password for 'http://Yogur@gitlab.test.net':
remote: Enumerating objects: 33, done.
remote: Counting objects: 100% (33/33), done.
remote: Compressing objects: 100% (14/14), done.
remote: Total 33 (delta 9), reused 33 (delta 9), pack-reused 0
Unpacking objects: 100% (33/33), done.