每天都是用真实机远程连接虚拟机做实验,由于脚本文件都是存放在同一个文件夹下且都是以.sh结尾,想要保存所有的脚本文件到真实机上,既然学了写脚本,那就用吧
实现要求
1.脚本自动执行
要想自动执行这个脚本,正好是真实机远程连接的虚拟机,希望退出虚拟机的时候自动执行,所有就将脚本写道/root/.bash_logout文件里,这个文件是root用户每次退出都会读取的文件
2.自动拷贝到真实机的某个目录下
使用scp命令远程拷贝,同时将虚拟机root用户的公钥加到真实机root用户下的/root/.ssh/下的认证文件中,采用密钥登录,省去输入密码的过程
3.找到脚本目录下的所有.sh文件,并将它全部拷贝到一个文本文件里以.txt结尾方便在windows主机上也方便查看
实现步骤
1.做好密钥登录的准备
1)修改真实机的ssh服务的配置文件
[root@localhost ~]# vim /etc/ssh/sshd_config PubkeyAuthentication yes --允许密钥认证登录 AuthorizedKeysFile .ssh/authorized_keys --指定认证文件的位置 GSSAPIAuthentication no ---这两项是加快连接速度 UseDNS no
2)在虚拟机上生成公钥并拷贝到真实机的认证文件中
#ssh-keygen Generating public/private rsa key pair. Enter file in which to save the key (/home/alvin/.ssh/id_rsa): Created directory '/home/alvin/.ssh'. Enter passphrase (empty for no passphrase): 要求输入加密短语 Enter same passphrase again: 再次要求输入加密短语 Your identification has been saved in /home/alvin/.ssh/id_rsa. 产生的私钥 Your public key has been saved in /home/alvin/.ssh/id_rsa.pub. 产生的公钥 The key fingerprint is: b0:94:a0:93:d7:2f:ca:6a:4e:c0:18:f9:1a:ab:19:8b alvin@master The key's randomart image is: +--[ RSA 2048]----+ | . | | . o o . | |o + . = | |oo o . + | |+.. o S | | = . . . | |+ . o | |o=.. | |Eoo | +-----------------+ #cd /root/.ssh # cat id_rsa.pub > authorized_keys # chmod 644 authorized_keys # scp authorized_keys root@10.0.2.68:/root/.ssh 将认证文件拷贝到真实机
此时虚拟机远程登录真实机不需要再输入密码了
[root@cmclient ~]# ssh 10.0.2.68 [root@localhost ~]#
2.在/root/.bash_logout文件中编写脚本
[root@cmclient test]# cat /root/.bash_logout # ~/.bash_logout #!/bin/bash #filename:bak.sh #autor:cm find /opt/rh/test -name "*.sh"|sort -n|xargs -I {} cat {} >/opt/rh/script.txt && echo "脚本文件备份成功!" if [ $? == 0 ] then scp /opt/rh/script.txt root@10.0.2.68:/root/桌面/script/ && echo "文件已经传送到主机" else echo "文件传送到主机失败" fi
3.执行结果
[root@cmclient test]# exit logout 脚本文件备份成功! script.txt 100% 2264 2.2KB/s 00:00 文件已经传送到主机 Connection to 10.0.7.15 closed. You have new mail in /var/spool/mail/root [root@localhost ~]#
查看真实机/root/桌面/script/文件夹下有一个script.txt文件,且成功拷贝了所有test文件夹下的所有脚本文件,宾果!