1 CA及证书申请
1.1 openssl命令
两种运行模式:
- 交互模式
- 批处理模式
三种子命令:
- 标准命令
- 消息摘要命令
- 加密命令
范例:
[root@centos8 ~]#openssl version OpenSSL 1.1.1 FIPS 11 Sep 2018 [root@centos8 ~]#openssl help Standard commands asn1parse ca ciphers cms crl crl2pkcs7 dgst dhparam dsa dsaparam ec ecparam enc engine errstr gendsa genpkey genrsa help list nseq ocsp passwd pkcs12 pkcs7 pkcs8 pkey pkeyparam [root@centos8 ~]#openssl OpenSSL> help Standard commands asn1parse ca ciphers cms crl crl2pkcs7 dgst dhparam ...... OpenSSL> ca --help Usage: ca [options] Valid options are: -help Display this summary -verbose Verbose output during processing -config val A config file ...... OpenSSL>q [root@centos8 ~]#1.1.1 openssl命令对称加密
工具:openssl enc, gpg算法:3des, aes, blowfish, twofishenc命令:帮助:man enc加密:
openssl enc -e -des3 -a -salt -in testfile -out testfile.cipher解密:
openssl enc -d -des3 -a -salt -in testfile.cipher -out testfile范例:
[root@centos8 ~]# rpm -qa openssl openssl-1.1.1c-15.el8.x86_64 [root@centos8 ~]# cd /data [root@centos8 data]# cp /etc/passwd ./ [root@centos8 data]# ls passwd #使用des3算法加密 [root@centos8 data]# openssl enc -e -des3 -a -salt -in passwd -out passwd.des enter des-ede3-cbc encryption password: #输入密码,最好满足复杂性要求 Verifying - enter des-ede3-cbc encryption password: *** WARNING : deprecated key derivation used. Using -iter or -pbkdf2 would be better. [root@centos8 data]# ls passwd passwd.des #解密文件 [root@centos8 data]# openssl enc -d -des3 -a -salt -in passwd.des -out passwd.out enter des-ede3-cbc decryption password: *** WARNING : deprecated key derivation used. Using -iter or -pbkdf2 would be better. #比较两个文件内容,无区别 [root@centos8 data]# diff passwd passwd.out #哈希加密值一致,内容相同 [root@centos8 data]# sha512sum passwd 9213e921ce4e23055b7a6be2a0a307a2f16d7620b6cf8d75576154b197cbb9ad70b694299cc45da0637faf9b3bf06182ab579064785c7f3747067fc279c274ae passwd [root@centos8 data]# sha512sum passwd.out 9213e921ce4e23055b7a6be2a0a307a2f16d7620b6cf8d75576154b197cbb9ad70b694299cc45da0637faf9b3bf06182ab579064785c7f3747067fc279c274ae passwd.out [root@centos8 data]#1.1.2 openssl命令单向哈希加密
工具:openssl dgst算法:md5sum, sha1sum, sha224sum,sha256sum…dgst命令:帮助:man dgst
openssl dgst -md5 [-hex默认] /PATH/SOMEFILE openssl dgst -md5 testfile md5sum /PATH/TO/SOMEFILE范例:
[root@centos8 data]# openssl md5 fstab #等同于openssl dgst -md5 filename MD5(fstab)= 2021cb0c2dde75edf78e06b2dde5d6c7 [root@centos8 data]# openssl sha512 fstab #等同于openssl dgst -sha512 filename SHA512(fstab)= 590720e46f49f8a16b359509cb5de60ea0309b024daba7048ba1213e89732971c716ad46b3576934a50916d3f673fa957cc9540bfce70d349d03870321d8bffb [root@centos8 data]# sha512sum fstab #同上 590720e46f49f8a16b359509cb5de60ea0309b024daba7048ba1213e89732971c716ad46b3576934a50916d3f673fa957cc9540bfce70d349d03870321d8bffb fstab [root@centos8 data]#1.1.3 openssl命令生成用户密码
passwd命令帮助:man sslpasswd
范例:
[root@centos8 /]# openssl passwd --help Usage: passwd [options] Valid options are: -help Display this summary -in infile Read passwords from file #从文件中读取密码列表 -noverify Never verify when reading password from terminal -quiet No warnings #生成密码过程中不输出任何信息 -table Format output as table -reverse Switch table columns -salt val Use provided salt #加点盐,可以增加算法的复杂度。盐和密码都相同,则加密的结果将一样。 -stdin Read passwords from stdin #从标准输入中获取要输入的密码 -6 SHA512-based password algorithm #基于sha512的算法代号 -5 SHA256-based password algorithm #基于sha256的算法代号 -apr1 MD5-based password algorithm, Apache variant -1 MD5-based password algorithm #基于MD5的算法代号 -aixmd5 AIX MD5-based password algorithm -crypt Standard Unix password algorithm (default) #不指定算法时,默认用-crypt -rand val Load the file(s) into the random number generator -writerand outfile Write random data to the specified file范例:
[root@centos8 /]# useradd wang [root@centos8 /]# echo magedu |passwd wang --stdin #查看wang的密码文件,其中A1h1SudFTQHOc3dP是随机加的salt位 [root@centos8 /]# getent shadow wang wang:$6$A1h1SudFTQHOc3dP$GRnZggTE6BIq6sLREesvxLYTuiLec6LkyLJ9.nlUbdQC4nsgBAEaSztwN2ERDbpbu1tu9hCcnxfy5jDa8l6Db/:18746:0:99999:7::: #设置wang的密码,不是原来的密码,即使salt一样,密码也不同 [root@centos8 /]# echo wangnew|openssl passwd -6 -salt A1h1SudFTQHOc3dP -stdin $6$A1h1SudFTQHOc3dP$gAa9.cf3pMrzOO7CszKh5Jhcacex8F9646tnrVZ4EGwWGm5GlFw2TTqy7r.xDL3DgBxtP.PrEF0ib5fDBKFlg. #只有密码和salt值都一致时,生成的用户密码才一致 [root@centos8 /]# echo magedu|openssl passwd -6 -salt A1h1SudFTQHOc3dP -stdin $6$A1h1SudFTQHOc3dP$GRnZggTE6BIq6sLREesvxLYTuiLec6LkyLJ9.nlUbdQC4nsgBAEaSztwN2ERDbpbu1tu9hCcnxfy5jDa8l6Db/ [root@centos8 /]# openssl passwd -6 -salt A1h1SudFTQHOc3dP magedu #同上 $6$A1h1SudFTQHOc3dP$GRnZggTE6BIq6sLREesvxLYTuiLec6LkyLJ9.nlUbdQC4nsgBAEaSztwN2ERDbpbu1tu9hCcnxfy5jDa8l6Db/范例:创建新用户同时指定密码,在CentOS和Ubuntu都通用
[root@centos8 /]# useradd -p `echo magedu |openssl passwd -6 -salt A1h1SudFTQHOc3dP -stdin` mage [root@centos8 /]# getent shadow mage #密码同wang的一致 mage:$6$A1h1SudFTQHOc3dP$GRnZggTE6BIq6sLREesvxLYTuiLec6LkyLJ9.nlUbdQC4nsgBAEaSztwN2ERDbpbu1tu9hCcnxfy5jDa8l6Db/:18746:0:99999:7:::范例:
openssl passwd -1 -salt SALT(最多8位) openssl passwd -1 –salt centos [root@centos8 /]# openssl passwd -1 -salt 123456 magedu $1$123456$QMBx42LRqK1ZWPfItmpYG0 #slat最多识别8位 [root@centos8 /]# openssl passwd -1 -salt 1234567890sdjflwefl magedu $1$12345678$Za7.XNG9d/GR4Ug3wV/I9/ #只识别了前8位1.1.4 openssl命令生成随机数
随机数生成器:伪随机数字,利用键盘和鼠标,块设备中断生成随机数/dev/random:仅从熵池返回随机数;随机数用尽,阻塞/dev/urandom:从熵池返回随机数;随机数用尽,会利用软件生成伪随机数,非阻塞帮助:man sslrand
openssl rand -base64 -hex NUM #-base64:使用base64 编码格式 #-hex:使用16进制编码格式 #NUM: 表示字节数,使用-hex,每个字符为十六进制,相当于4位二进制,出现的字符数为NUM*2 [root@centos8 ~]# openssl rand -base64 -hex 4 b3f6a2f8 [root@centos8 ~]# openssl rand -base64 -hex 2 f77f [root@centos8 ~]# openssl rand -base64 4 LeOEDg== [root@centos8 ~]# openssl rand -base64 9 KuiYwJ7QiKaI [root@centos8 ~]# openssl rand -base64 9 |head -c15 D2Q2vUkWmpxq [root@centos8 ~]# openssl rand -base64 9 |head -c6 /SI0Bn范例:生成随机10位长度密码
[root@centos8 ~]#openssl rand -base64 9 |head -c10 ip97t6qQes[root@centos8 ~]# [root@centos8 ~]#tr -dc '[:alnum:]' < /dev/urandom |head -c10 DO2mDp3eZu[root@centos8 ~]#1.1.5 openssl命令实现 PKI
公钥加密:算法:RSA, ELGamal工具:gpg, openssl rsautl(man rsautl)数字签名:算法:RSA, DSA, ELGamal DSA仅支持签名;而RSA支持加密和签名
密钥交换:算法:dhDSA:Digital Signature AlgorithmDSS:Digital Signature StandardRSA:openssl命令生成密钥对儿:man genrsa生成私钥
openssl genrsa -out /PATH/TO/PRIVATEKEY.FILE [-des3] [NUM_BITS,默认2048]范例:
方法一:生成对称秘钥的私钥,通过设置严格的权限(600权限)实现安全,应用更广泛 [root@centos8 data]# (umask 077;openssl genrsa -out app.key 2048) Generating RSA private key, 2048 bit long modulus (2 primes) ............................+++++ .........+++++ e is 65537 (0x010001) [root@centos8 data]# ll app.key -rw------- 1 root root 1675 Apr 29 21:41 app.key [root@centos8 data]# cat app.key -----BEGIN RSA PRIVATE KEY----- -----END RSA PRIVATE KEY----- [root@centos8 data]# 方法二:使用des算法生成加密的私钥,此方式更安全,但是不方便 [root@centos8 data]# openssl genrsa -out /data/app1.key -des3 2048 Generating RSA private key, 2048 bit long modulus (2 primes) ...............................................+++++ ........+++++ e is 65537 (0x010001) Enter pass phrase for /data/app1.key: #输入两遍密码 Verifying - Enter pass phrase for /data/app1.key: [root@centos8 data]# ll app* -rw------- 1 root root 1751 Apr 29 21:52 app1.key -rw------- 1 root root 1675 Apr 29 21:41 app.key [root@centos8 data]# cat app1.key -----BEGIN RSA PRIVATE KEY----- Proc-Type: 4,ENCRYPTED DEK-Info: DES-EDE3-CBC,52D409FBE7DC4539 #使用des算法加密 -----END RSA PRIVATE KEY----- [root@centos8 ~]#从私钥中提取出公钥
openssl rsa -in PRIVATEKEYFILE –pubout –out PUBLICKEYFILE范例:
openssl rsa –in test.key –pubout –out test.key.pub范例:
#方法一提取公钥 [root@centos8 data]# openssl rsa -in app.key -pubout -out app.key.pub writing RSA key [root@centos8 data]# ll app.key* -rw------- 1 root root 1675 Apr 29 21:41 app.key -rw-r--r-- 1 root root 451 Apr 29 22:14 app.key.pub [root@centos8 data]# cat app.key.pub -----BEGIN PUBLIC KEY----- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA1yUux1AcK61oeQAjJkV+ 988wPSZwTk/CG6RSghs3hXmFQvm2JU69D7F61CHwTft6ERDF9JYr3IEOcW+btN2Z uC9TpPBzk/mdkEcp8lFLKVDyX0yS1+Tog/COYp7dxSrC6XwMn/cAIz/+z6m0TucO VRdpgjnfWFzWoyWWK8BmOiBpNvlSnamc8FefhTgv1hUtfhi2DAP4fOTWWkzMl8Bs q97h9uoizT/YdUphvMDE76zV3B3z2K+2hW+Cy01L9APvQ4E/DNvGCQEGWKKfoX24 NVse8Z4ZWBRCgJ3FwZg5gI2TLxU/aNyecr5+BwLf8XULtrvofXjpX1EqU6xXrmla aQIDAQAB -----END PUBLIC KEY----- #方法二提取公钥 [root@centos8 data]# openssl rsa -in app1.key -pubout -out app1.key.pub Enter pass phrase for app1.key: #需要输入密码 writing RSA key [root@centos8 data]# ll app1.key* -rw------- 1 root root 1751 Apr 29 21:52 app1.key -rw-r--r-- 1 root root 451 Apr 29 22:16 app1.key.pub [root@centos8 data]# cat app1.key.pub -----BEGIN PUBLIC KEY----- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyR2KCnWFgBSJEHmVqCpQ S2CbX296eCQEsnD9/PoIA2/67HzfBANT6w/MKCrJ/ngQ+SwF8XX+OBewj4jVTDKE G3Pk2Ud58JUD7H7XNhFXFOOhLtzFm4ojR4XN6jNE+0ififutKnpuZNBAbOC+x7o4 HV5ZXz01eqAMFlUfEnmZGScvWP3jC2beq/zfxize+VmqlKpI19jT2RSvx0dzjEXA L8H8dn3NoCjuv54FKnQoFNG89+CZmF2qDEy+yNeMp8oH3x6LQq8FeFitRz7bBiMs 51WQliQ6nRUHL71TZLVIQ+ZtxZ0r8Sv/g1eHAs7M01jPd0WIofvidABy4SVOqep+ PQIDAQAB -----END PUBLIC KEY-----范例:生成加密的私钥,并解密
[root@centos8 data]# openssl genrsa -out app2.key -des3 1024 Generating RSA private key, 1024 bit long modulus (2 primes) ...........+++++ .....+++++ e is 65537 (0x010001) Enter pass phrase for app2.key: Verifying - Enter pass phrase for app2.key: [root@centos8 data]# ll app2.key -rw------- 1 root root 963 Apr 29 22:25 app2.key [root@centos8 data]# cat app2.key -----BEGIN RSA PRIVATE KEY----- Proc-Type: 4,ENCRYPTED DEK-Info: DES-EDE3-CBC,9A09EEF750FE8B2F -----END RSA PRIVATE KEY----- [root@centos8 data]# openssl rsa -in app2.key -out app2.key.out Enter pass phrase for app2.key: writing RSA key [root@centos8 data]# ll app2.key* -rw------- 1 root root 963 Apr 29 22:25 app2.key -rw------- 1 root root 887 Apr 29 22:27 app2.key.out [root@centos8 data]# cat app2.key.out -----BEGIN RSA PRIVATE KEY----- -----END RSA PRIVATE KEY----- [root@centos8 data]#1.2 建立私有CA实现证书申请颁发
建立私有CA:OpenCA:OpenCA开源组织使用Perl对OpenSSL进行二次开发而成的一套完善的PKI免费软件openssl:相关包 openssl和openssl-libs证书申请及签署步骤:
范例:openssl-libs包
[root@centos8 ~]#rpm -ql openssl-libs /etc/pki/tls /etc/pki/tls/certs /etc/pki/tls/ct_log_list.cnf /etc/pki/tls/misc /etc/pki/tls/openssl.cnf /etc/pki/tls/private /usr/lib/.build-id /usr/lib/.build-id/27 /usr/lib/.build-id/27/e3d5f8d63820f2fef5de2026878156fceceddbopenssl的配置文件:
/etc/pki/tls/openssl.cnf三种策略:match匹配、optional可选、supplied提供
- match:要求申请填写的信息跟CA设置信息必须一致
- optional:可有可无,跟CA设置信息可不一致
- supplied:必须填写这项申请信息
范例:
[root@centos8 ~]#cat /etc/pki/tls/openssl.cnf # ...... #################################################################### [ ca ] default_ca = CA_default # The default ca section #################################################################### [ CA_default ] dir = /etc/pki/CA # Where everything is kept certs = $dir/certs # Where the issued certs are kept crl_dir = $dir/crl # Where the issued crl are kept database = $dir/index.txt # database index file. #unique_subject = no # Set to 'no' to allow creation of # several certs with same subject. new_certs_dir = $dir/newcerts # default place for new certs. certificate = $dir/cacert.pem # The CA certificate serial = $dir/serial # The current serial number crlnumber = $dir/crlnumber # the current crl number # must be commented out to leave a V1 CRL crl = $dir/crl.pem # The current CRL private_key = $dir/private/cakey.pem# The private key RANDFILE = $dir/private/.rand # private random number file x509_extensions = usr_cert # The extensions to add to the cert # Comment out the following two lines for the "traditional" # (and highly broken) format. name_opt = ca_default # Subject Name options cert_opt = ca_default # Certificate field options default_days = 365 # how long to certify for default_crl_days= 30 # how long before next CRL default_md = sha256 # use SHA-256 by default preserve = no # keep passed DN ordering policy = policy_match # For the CA policy [ policy_match ] countryName = match stateOrProvinceName = match organizationName = match organizationalUnitName = optional commonName = supplied emailAddress = optional # For the 'anything' policy # At this point in time, you must list all acceptable 'object' # types. [ policy_anything ] countryName = optional stateOrProvinceName = optional localityName = optional organizationName = optional organizationalUnitName = optional commonName = supplied emailAddress = optional ......1.2.1 创建私有CA
1、创建CA所需要的文件
#生成证书索引数据库文件 touch /etc/pki/CA/index.txt #指定第一个颁发证书的序列号 echo 01 > /etc/pki/CA/serial2、 生成CA私钥
cd /etc/pki/CA/ (umask 066; openssl genrsa -out private/cakey.pem 2048)3、生成CA自签名证书
openssl req -new -x509 -key /etc/pki/CA/private/cakey.pem -days 3650 -out /etc/pki/CA/cacert.pem选项说明:
-new #生成新证书签署请求 -x509 #专用于CA生成自签证书 -key #生成请求时用到的私钥文件 -days n #证书的有效期限 -out /PATH/TO/SOMECERTFILE #证书的保存路径国家代码:https://country-code.cl/
范例:生成自签名证书
[root@centos8 ~]#openssl req -utf8 -newkey rsa:1024 -subj "/CN=www.magedu.org" -keyout app.key -nodes -x509 -out app.crt Generating a RSA private key ...........................+++++ ...+++++ writing new private key to 'app.key' ----- [root@centos8 ~]#openssl x509 -in app.crt -noout -text Certificate: Data: Version: 3 (0x2) Serial Number: 39:9e:7c:e3:9a:0f:e3:d3:62:ea:8f:02:c9:cd:1e:f3:4a:77:cb:ff Signature Algorithm: sha256WithRSAEncryption Issuer: CN = www.magedu.org Validity Not Before: Feb 4 15:51:39 2020 GMT Not After : Mar 5 15:51:39 2020 GMT Subject: CN = www.magedu.org [root@centos8 ~]#1.2.2 申请证书并颁发证书
1、为需要使用证书的主机生成生成私钥
(umask 066; openssl genrsa -out /data/test.key 2048)2、为需要使用证书的主机生成证书申请文件
openssl req -new -key /data/test.key -out /data/test.csr3、在CA签署证书并将证书颁发给请求者
openssl ca -in /tmp/test.csr -out /etc/pki/CA/certs/test.crt -days 100注意:默认要求 国家,省,公司名称三项必须和CA一致4、查看证书中的信息:
openssl x509 -in /PATH/FROM/CERT_FILE -noout -text|issuer|subject|serial|dates #查看指定编号的证书状态 openssl ca -status SERIAL1.2.3 吊销证书
在客户端获取要吊销的证书的serial
openssl x509 -in /PATH/FROM/CERT_FILE -noout -serial -subject在CA上,根据客户提交的serial与subject信息,对比检验是否与index.txt文件中的信息一致,吊销证书:
openssl ca -revoke /etc/pki/CA/newcerts/SERIAL.pem指定第一个吊销证书的编号,注意:第一次更新证书吊销列表前,才需要执行更新证书吊销列表
echo 01 > /etc/pki/CA/crlnumber openssl ca -gencrl -out /etc/pki/CA/crl.pem查看crl文件:
openssl crl -in /etc/pki/CA/crl.pem -noout -text1.2.4 CentOS 7 创建自签名证书
临时用一次,只自己使用,则不需要创建CA,创建自签名证书就可以了。
#两个步骤就可以创建自签名证书 cd /etc/pki/tls/certs make test.crt [root@centos7 ~]# cd /etc/pki/tls/certs [root@centos7 certs]# ll total 472 -r--r--r-- 1 root root 211658 May 8 13:54 ca-bundle.crt -r--r--r-- 1 root root 257889 May 8 13:54 ca-bundle.trust.crt -rwxr-xr-x 1 root root 610 May 8 13:54 make-dummy-cert -rw-r--r-- 1 root root 2516 May 8 13:54 Makefile -rwxr-xr-x 1 root root 829 May 8 13:54 renew-dummy-cert [root@centos7 certs]# make test.crt umask 77 ; \ /usr/bin/openssl genrsa -aes128 2048 > test.key Generating RSA private key, 2048 bit long modulus .............................................................................................................................................................+++ ........................................................................+++ e is 65537 (0x10001) Enter pass phrase: Verifying - Enter pass phrase: umask 77 ; \ /usr/bin/openssl req -utf8 -new -key test.key -x509 -days 365 -out test.crt Enter pass phrase for test.key: You are about to be asked to enter information that will be incorporated into your certificate request. What you are about to enter is what is called a Distinguished Name or a DN. There are quite a few fields but you can leave some blank For some fields there will be a default value, If you enter '.', the field will be left blank. ----- Country Name (2 letter code) [XX]:CN State or Province Name (full name) []:Hebei Locality Name (eg, city) [Default City]:HB Organization Name (eg, company) [Default Company Ltd]:magedu Organizational Unit Name (eg, section) []:IT Common Name (eg, your name or your server's hostname) []:magedu.org Email Address []:admin@magedu.org [root@centos7 certs]# ll test* -rw------- 1 root root 1306 May 8 14:25 test.crt -rw------- 1 root root 1766 May 8 14:24 test.key [root@centos7 certs]# openssl x509 -in test.crt -noout -text Certificate: Data: Version: 3 (0x2) Serial Number: d0:25:f5:5c:ea:21:21:84 Signature Algorithm: sha256WithRSAEncryption Issuer: C=CN, ST=Hebei, L=HB, O=magedu, OU=IT, CN=magedu.org/emailAddress=admin@magedu.org Validity Not Before: May 8 06:30:54 2021 GMT Not After : May 8 06:30:54 2022 GMT Subject: C=CN, ST=Hebei, L=HB, O=magedu, OU=IT, CN=magedu.org/emailAddress=admin@magedu.org [root@centos7 certs]# openssl x509 -in test.crt -noout -subject subject= /C=CN/ST=Hebei/L=HB/O=magedu/OU=IT/CN=magedu.org/emailAddress=admin@magedu.org [root@centos7 certs]# openssl x509 -in test.crt -noout -issuer issuer= /C=CN/ST=Hebei/L=HB/O=magedu/OU=IT/CN=magedu.org/emailAddress=admin@magedu.org [root@centos7 certs]# openssl x509 -in test.crt -noout -dates notBefore=May 8 06:30:54 2021 GMT notAfter=May 8 06:30:54 2022 GMT [root@centos7 certs]# openssl x509 -in test.crt -noout -serial serial=D025F55CEA2121841.2.5 实战案例:在CentOS8上实现私有CA和证书申请
1.2.5.1 创建CA相关目录和文件
[root@centos8 ~]#mkdir -pv /etc/pki/CA/{certs,crl,newcerts,private} mkdir: created directory '/etc/pki/CA' mkdir: created directory '/etc/pki/CA/certs' mkdir: created directory '/etc/pki/CA/crl' mkdir: created directory '/etc/pki/CA/newcerts' mkdir: created directory '/etc/pki/CA/private' [root@centos8 ~]#tree /etc/pki/CA/ /etc/pki/CA/ ├── certs ├── crl ├── newcerts └── private 4 directories, 0 files [root@centos8 ~]#touch /etc/pki/CA/index.txt [root@centos8 ~]#echo 0F > /etc/pki/CA/serial1.2.5.2 创建CA的私钥
#生成CA私钥 [root@centos8 ~]#cd /etc/pki/CA [root@centos8 CA]#(umask 066;openssl genrsa -out private/cakey.pem 2048) Generating RSA private key, 2048 bit long modulus ..........+++ ........+++ e is 65537 (0x10001) [root@centos8 CA]#tree . ├── certs ├── crl ├── newcerts └── private └── cakey.pem 4 directories, 1 file [root@centos8 CA]#ll private/ total 4 -rw------- 1 root root 1675 May 3 08:35 cakey.pem [root@centos8 CA]#cat private/cakey.pem -----BEGIN RSA PRIVATE KEY----- -----END RSA PRIVATE KEY----- [root@centos8 CA]#1.2.5.3 给CA颁发自签名证书
#生成CA自签名证书 [root@centos8 CA]#openssl req -new -x509 -key /etc/pki/CA/private/cakey.pem -days 3650 -out /etc/pki/CA/cacert.pem <<EOF > CN > Beijing > BJ > magedu > IT > ca.magedu.org > admin@magedu.org > > > EOF [root@centos8 CA]#tree /etc/pki/CA /etc/pki/CA ├── cacert.pem ├── certs ├── crl ├── newcerts └── private └── cakey.pem 4 directories, 2 files [root@centos8 CA]#cat /etc/pki/CA/cacert.pem -----BEGIN CERTIFICATE----- -----END CERTIFICATE----- [root@centos8 CA]#openssl x509 -in /etc/pki/CA/cacert.pem -noout -text Certificate: Data: Version: 3 (0x2) Serial Number: 96:9e:70:c7:6c:a1:34:83 Signature Algorithm: sha256WithRSAEncryption Issuer: C=CN, ST=Beijing, L=BJ, O=magedu, OU=IT, CN=ca.magedu.org/emailAddress=admin@magedu.org Validity Not Before: May 3 00:38:51 2021 GMT Not After : May 1 00:38:51 2031 GMT Subject: C=CN, ST=Beijing, L=BJ, O=magedu, OU=IT, CN=ca.magedu.org/emailAddress=admin@magedu.org [root@centos8 ~]# sz /etc/pki/CA/cacert.pem #将文件cacert.pem传到windows上,修改文件名为cacert.pem.crt,双击查看1.2.5.4 用户生成私钥和证书申请
[root@centos8 ~]#mkdir -p /data/app1 [root@centos8 ~]#(umask 066;openssl genrsa -out /data/app1/app1.key 2048) Generating RSA private key, 2048 bit long modulus .......................................................+++ ...............................................................+++ e is 65537 (0x10001)1.2.5.5 CA颁发证书
[root@centos8 ~]#openssl req -new -key /data/app1/app1.key -out /data/app1/app1.csr <<EOF > CN > Beijing > BJ > magedu > sales > app1.magedu.org > app1@magedu.org > > > EOF #颁发证书,不加-days,默认是一年有效期 [root@centos8 ~]#openssl ca -in /data/app1/app1.csr -out /etc/pki/CA/certs/app1.crt Using configuration from /etc/pki/tls/openssl.cnf Check that the request matches the signature Signature ok Certificate Details: Serial Number: 15 (0xf) Validity Not Before: May 3 01:52:00 2021 GMT Not After : May 3 01:52:00 2022 GMT Subject: countryName = CN stateOrProvinceName = Beijing organizationName = magedu organizationalUnitName = sales commonName = app1.magedu.org emailAddress = app1@magedu.org X509v3 extensions: X509v3 Basic Constraints: CA:FALSE Netscape Comment: OpenSSL Generated Certificate X509v3 Subject Key Identifier: D1:AF:D5:13:D4:16:66:7C:6C:C0:48:A5:A2:3D:4B:D8:36:DE:28:A3 X509v3 Authority Key Identifier: keyid:EA:A9:86:6A:1F:D8:66:83:1D:EB:06:AA:6A:3B:C5:00:04:21:1A:46 Certificate is to be certified until May 3 01:52:00 2022 GMT (365 days) Sign the certificate? [y/n]:y 1 out of 1 certificate requests certified, commit? [y/n]y Write out database with 1 new entries Data Base Updated [root@centos8 ~]#tree /etc/pki/CA /etc/pki/CA ├── cacert.pem ├── certs │ ├── app1.crt │ └── app2.crt ├── crl ├── index.txt ├── index.txt.attr ├── index.txt.old ├── newcerts │ └── 0F.pem ├── private │ └── cakey.pem ├── serial └── serial.old 4 directories, 10 files1.2.5.6 查看证书
[root@centos8 ~]#cat /etc/pki/CA/certs/app1.crt Certificate: Data: Version: 3 (0x2) Serial Number: 15 (0xf) Signature Algorithm: sha256WithRSAEncryption Issuer: C=CN, ST=Beijing, L=BJ, O=magedu, OU=IT, CN=ca.magedu.org/emailAddress=admin@magedu.org #issuer'发布者 Validity Not Before: May 3 01:52:00 2021 GMT Not After : May 3 01:52:00 2022 GMT Subject: C=CN, ST=Beijing, O=magedu, OU=sales, CN=app1.magedu.org/emailAddress=app1@magedu.org #subject使用者 [root@centos8 ~]#openssl x509 -in /etc/pki/CA/certs/app1.crt -noout -text Certificate: Data: Version: 3 (0x2) Serial Number: 15 (0xf) Signature Algorithm: sha256WithRSAEncryption Issuer: C=CN, ST=Beijing, L=BJ, O=magedu, OU=IT, CN=ca.magedu.org/emailAddress=admin@magedu.org Validity Not Before: May 3 01:52:00 2021 GMT Not After : May 3 01:52:00 2022 GMT Subject: C=CN, ST=Beijing, O=magedu, OU=sales, CN=app1.magedu.org/emailAddress=app1@magedu.org [root@centos8 ~]#openssl x509 -in /etc/pki/CA/certs/app1.crt -noout -issuer issuer= /C=CN/ST=Beijing/L=BJ/O=magedu/OU=IT/CN=ca.magedu.org/emailAddress=admin@magedu.org [root@centos8 ~]#openssl x509 -in /etc/pki/CA/certs/app1.crt -noout -subject subject= /C=CN/ST=Beijing/O=magedu/OU=sales/CN=app1.magedu.org/emailAddress=app1@magedu.org [root@centos8 ~]#openssl x509 -in /etc/pki/CA/certs/app1.crt -noout -dates notBefore=May 3 01:52:00 2021 GMT notAfter=May 3 01:52:00 2022 GMT [root@centos8 ~]#openssl x509 -in /etc/pki/CA/certs/app1.crt -noout -serial serial=0F #验证指定编号对应证书的有效性 [root@centos8 ~]#openssl ca -status 0F Using configuration from /etc/pki/tls/openssl.cnf 0F=Valid (V) [root@centos8 ~]#cat /etc/pki/CA/index.txt V 220503015200Z 0F unknown /C=CN/ST=Beijing/O=magedu/OU=sales/CN=app1.magedu.org/emailAddress=app1@magedu.org [root@centos8 ~]#cat /etc/pki/CA/index.txt.old [root@centos8 ~]#cat /etc/pki/CA/serial 10 [root@centos8 ~]#cat /etc/pki/CA/serial.old 0F [root@centos8 ~]# [root@centos8 ~]# sz /etc/pki/CA/certs/app1.crt #将文件app1.crt传到windows上,双击查看1.2.5.7 证书的信任
默认生成的证书,在windows上是不被信任的,可以通过下面的操作实现。
方法1:打开浏览器---工具---internet选项---内容---证书---受信任的根证书颁发机构---导入---浏览---找到cacert.pem.crt证书---安装证书---完成
方法2:双击导出的cacert.pem.crt证书---安装证书---选择将所有的证书都放入下列存储---浏览---受信任的根证书颁发机构---下一步---安装证书---完成
完成后,无论是根证书还是app1子证书,都显示正常
1.2.5.8 将证书相关文件发送到用户端使用
[root@centos8 ~]#cp /etc/pki/CA/certs/app1.crt /data/app1 [root@centos8 ~]#ll /data/app1 total 16 -rw-r--r-- 1 root root 4601 May 3 15:12 app1.crt -rw-r--r-- 1 root root 1050 May 3 09:51 app1.csr -rw------- 1 root root 1679 May 3 09:36 app1.key1.2.5.9 容易出现的问题
1、index.txt和serial文件在颁发证书时需要使用,如果不存在,会出现以下错误提示
#查看CA目录,无index.txt和serial文件 [root@centos8 ~]#ls /etc/pki/CA/{index.txt,serial} ls: cannot access /etc/pki/CA/index.txt: No such file or directory ls: cannot access /etc/pki/CA/serial: No such file or directory #创建app2用户,并生成私钥和证书申请 [root@centos8 ~]#mkdir -p /data/app2 [root@centos8 ~]#(umask 066;openssl genrsa -out /data/app2/app2.key 2048) [root@centos8 ~]#openssl req -new -key /data/app2/app2.key -out /data/app2/app2.csr You are about to be asked to enter information that will be incorporated into your certificate request. What you are about to enter is what is called a Distinguished Name or a DN. There are quite a few fields but you can leave some blank For some fields there will be a default value, If you enter '.', the field will be left blank. ----- Country Name (2 letter code) [XX]:CN State or Province Name (full name) []:hebei #填写与ca根证书(Beijing)不一致 Locality Name (eg, city) [Default City]:hb Organization Name (eg, company) [Default Company Ltd]:magedu.org Organizational Unit Name (eg, section) []:sales Common Name (eg, your name or your server's hostname) []:app2.magedu.org Email Address []: Please enter the following 'extra' attributes to be sent with your certificate request A challenge password []: An optional company name []: #颁发证书,出现unalbe to open /etc/pki/CA/index.txt [root@centos8 ~]#openssl ca -in /data/app2/app2.csr -out /etc/pki/CA/certs/app2.crt Using configuration from /etc/pki/tls/openssl.cnf /etc/pki/CA/index.txt: No such file or directory unable to open '/etc/pki/CA/index.txt' 140308105873296:error:02001002:system library:fopen:No such file or directory:bss_file.c:402:fopen('/etc/pki/CA/index.txt','r') 140308105873296:error:20074002:BIO routines:FILE_CTRL:system lib:bss_file.c:404: [root@centos8 ~]#touch /etc/pki/CA/index.txt #只建立index.txt文件,无serial的提示信息如下 [root@centos8 ~]#openssl ca -in /data/app2/app2.csr -out /etc/pki/CA/certs/app2.crt Using configuration from /etc/pki/tls/openssl.cnf /etc/pki/CA/serial: No such file or directory error while loading serial number 139743888226192:error:02001002:system library:fopen:No such file or directory:bss_file.c:402:fopen('/etc/pki/CA/serial','r') 139743888226192:error:20074002:BIO routines:FILE_CTRL:system lib:bss_file.c:404: [root@centos8 ~]#echo 0F >/etc/pki/CA/serial [root@centos8 ~]#ll /etc/pki/CA/{index.txt,serial} -rw-r--r-- 1 root root 111 May 3 09:52 /etc/pki/CA/index.txt -rw-r--r-- 1 root root 3 May 3 09:52 /etc/pki/CA/serial默认有三项内容必须和CA一致:国家,省份,组织,如果不同,会出现下面的提示
[root@centos8 ~]#openssl ca -in /data/app2/app2.csr -out /etc/pki/CA/certs/app2.crt Using configuration from /etc/pki/tls/openssl.cnf Check that the request matches the signature Signature ok The stateOrProvinceName field needed to be the same in the CA certificate (Beijing) and the request (hebei)1.2.5.10 证书的吊销
查看当前的证书
#查看一下生成的两个子证书app1.crt和app2.crt [root@centos8 ~]#tree /etc/pki/CA /etc/pki/CA ├── cacert.pem ├── certs │ ├── app1.crt │ └── app2.crt ├── crl ├── index.txt ├── index.txt.attr ├── index.txt.attr.old ├── index.txt.old ├── newcerts │ ├── 0F.pem │ └── 10.pem ├── private │ └── cakey.pem ├── serial └── serial.old 4 directories, 12 files [root@centos8 ~]#cd /etc/pki/CA [root@centos8 CA]#cat index.txt V 220503015200Z 0F unknown /C=CN/ST=Beijing/O=magedu/OU=sales/CN=app1.magedu.org/emailAddress=app1@magedu.org V 240128081624Z 10 unknown /C=CN/ST=Beijing/O=magedu/OU=sales/CN=app2.magedu.org/emailAddress=app2@magedu.org [root@centos8 CA]#cat index.txt.attr unique_subject = yes [root@centos8 CA]#cat index.txt.attr.old unique_subject = yes [root@centos8 CA]#cat index.txt.old V 220503015200Z 0F unknown /C=CN/ST=Beijing/O=magedu/OU=sales/CN=app1.magedu.org/emailAddress=app1@magedu.org [root@centos8 CA]#cat serial #serial显示的是下一个证书编号 11 [root@centos8 CA]#cat serial.old #old里显示的是当前最后一个证书编号 10吊销app2证书
[root@centos8 CA]#openssl ca -revoke newcerts/10.pem Using configuration from /etc/pki/tls/openssl.cnf Revoking Certificate 10. Data Base Updated [root@centos8 CA]#openssl ca -status 10 Using configuration from /etc/pki/tls/openssl.cnf 10=Revoked (R) [root@centos8 CA]#cat index.txt] cat: index.txt]: No such file or directory [root@centos8 CA]#cat index.txt V 220503015200Z 0F unknown /C=CN/ST=Beijing/O=magedu/OU=sales/CN=app1.magedu.org/emailAddress=app1@magedu.org R 240128081624Z 210503082108Z 10 unknown /C=CN/ST=Beijing/O=magedu/OU=sales/CN=app2.magedu.org/emailAddress=app2@magedu.org [root@centos8 CA]#1.2.5.11 生成证书吊销列表文件
[root@centos8 CA]#openssl ca -gencrl -out /etc/pki/CA/crl.pem Using configuration from /etc/pki/tls/openssl.cnf /etc/pki/CA/crlnumber: No such file or directory error while loading CRL number 140148320987024:error:02001002:system library:fopen:No such file or directory:bs s_file.c:402:fopen('/etc/pki/CA/crlnumber','r') 140148320987024:error:20074002:BIO routines:FILE_CTRL:system lib:bss_file.c:404: [root@centos8 CA]#echo 01 >/etc/pki/CA/crlnumber [root@centos8 CA]#openssl ca -gencrl -out /etc/pki/CA/crl.pem Using configuration from /etc/pki/tls/openssl.cnf [root@centos8 CA]#cat /etc/pki/CA/crlnumber 02 [root@centos8 CA]#openssl crl -in /etc/pki/CA/crl.pem -noout -text Certificate Revocation List (CRL): Version 2 (0x1) Signature Algorithm: sha256WithRSAEncryption Issuer: /C=CN/ST=Beijing/L=BJ/O=magedu/OU=IT/CN=ca.magedu.org/emailAddress=admin@magedu.org Last Update: May 3 08:25:46 2021 GMT Next Update: Jun 2 08:25:46 2021 GMT CRL extensions: X509v3 CRL Number: 1 Revoked Certificates: Serial Number: 10 [root@centos8 CA]#sz /etc/pki/CA/crl.pem #将此文件crl.pem传到windows上并改后缀为crl.pem.crl,双击可以查看以下显示1.2.6 脚本实现CA根证书创建和应用程序证书颁发
[root@centos8 data]# cat ca_fun.sh #!/bin/bash . /etc/init.d/functions root_ca () { #1 CA证书的创建 #创建CA相关目录和文件 mkdir -pv /etc/pki/CA/{certs,crl,newcerts,private} &>/dev/null touch /etc/pki/CA/index.txt &>/dev/null echo 00 > /etc/pki/CA/serial && action "初始化CA相关目录和文件成功" true #创建CA的私钥 cd /etc/pki/CA (umask 066; openssl genrsa -out private/cakey.pem 2048) &>/dev/null #生成CA自签名证书 openssl req -new -x509 -key /etc/pki/CA/private/cakey.pem -days 3650 -out /etc/pki/CA/cacert.pem &>/dev/null <<EOF CN Beijing BJ magedu IT ca.magedu.org admin@magedu.org EOF [ $? -eq 0 ] && action "CA证书创建成功" true } user_ca (){ #2 用户申请证书 #用户生成私钥和证书申请 read -p "请输入要申请证书的应用程序名称及部门使用者(用空格隔开):" ca_app OU_Name mkdir -p /certs/$ca_app (umask 066; openssl genrsa -out /certs/$ca_app/$ca_app.key 2048) &>/dev/null openssl req -new -key /certs/$ca_app/$ca_app.key -out /certs/$ca_app/$ca_app.csr &>/dev/null <<EOF CN Beijing BJ magedu $OU_Name $ca_app.magedu.org $ca_app@magedu.org EOF [ $? -eq 0 ] && action "用户私钥创建成功" true #颁发证书 openssl ca -in /certs/$ca_app/$ca_app.csr -out /etc/pki/CA/certs/$ca_app.crt -days 1000 &>/dev/null <<EOF y y EOF [ $? -eq 0 ] && action "颁发用户证书成功" true } PS3="请选择:" menu=' 创建根CA证书 给用户颁发证书 退出 ' select M in $menu;do case $REPLY in 1) root_ca ;; 2) user_ca ;; 3) exit ;; *) echo "请输入正确的数字" esac done [root@centos8 data]# rm /etc/pki/CA -rf [root@centos8 data]# rm /certs -rf [root@centos8 data]# bash ca_fun.sh 1) 创建根CA证书 2) 给用户颁发证书 3) 退出 请选择:1 初始化CA相关目录和文件成功 [ OK ] CA证书创建成功 [ OK ] 请选择:2 请输入要申请证书的应用程序名称及部门使用者(用空格隔开):tomcat shengchan 用户私钥创建成功 [ OK ] 颁发用户证书成功 [ OK ] 请选择:2 请输入要申请证书的应用程序名称及部门使用者(用空格隔开):http 用户私钥创建成功 [ OK ] 颁发用户证书成功 [ OK ] 请选择:3 [root@centos8 data]# cat /etc/pki/CA/certs/tomcat.crt Certificate: Data: Version: 3 (0x2) Serial Number: 0 (0x0) Signature Algorithm: sha256WithRSAEncryption Issuer: C=CN, ST=Beijing, L=BJ, O=magedu, OU=IT, CN=ca.magedu.org/emailAddress=admin@magedu.org Validity Not Before: May 8 03:26:19 2021 GMT Not After : Feb 2 03:26:19 2024 GMT Subject: C=CN, ST=Beijing, O=magedu, OU=shengchan, CN=tomcat.magedu.org/emailAddress=tomcat@magedu.org #使用部门是shengchan [root@centos8 data]# cat /etc/pki/CA/certs/http.crt Certificate: Data: Version: 3 (0x2) Serial Number: 1 (0x1) Signature Algorithm: sha256WithRSAEncryption Issuer: C=CN, ST=Beijing, L=BJ, O=magedu, OU=IT, CN=ca.magedu.org/emailAddress=admin@magedu.org Validity Not Before: May 8 03:26:27 2021 GMT Not After : Feb 2 03:26:27 2024 GMT Subject: C=CN, ST=Beijing, O=magedu, CN=http.magedu.org/emailAddress=http@magedu.org #未指定使用部门,OU为空2 ssh服务
2.1 ssh服务介绍
ssh: secure shell, protocol, 22/tcp, 安全的远程登录,实现加密通信,代替传统的 telnet 协议(不加密)具体的软件实现:
- OpenSSH:ssh协议的开源实现,CentOS 默认安装
- dropbear:另一个ssh协议的开源项目的实现
SSH 协议版本
- v1:基于CRC-32做MAC,不安全;man-in-middle
-
v2:双方主机协议选择安全的MAC方式,基于DH算法做密钥交换,基于RSA或DSA实现身份认证
2.1.1 公钥交换原理
- 客户端发起链接请求
- 服务端返回自己的公钥,以及一个会话ID(这一步客户端得到服务端公钥)
- 客户端生成密钥对
- 客户端用自己的公钥异或会话ID,计算出一个值Res,并用服务端的公钥加密
- 客户端发送加密后的值到服务端,服务端用私钥解密,得到Res
- 服务端用解密后的值Res异或会话ID,计算出客户端的公钥(这一步服务端得到客户端公钥)
- 最终:双方各自持有三个秘钥,分别为自己的一对公、私钥,以及对方的公钥,之后的所有通讯都会被加密
2.2 openssh 服务
OpenSSH是SSH (Secure SHell) 协议的免费开源实现,一般在各种Linux版本中会默认安装,基于C/S结构
Openssh软件相关包:
- openssh
- openssh-clients
- openssh-server
范例:相关包
[root@centos7 ~]# rpm -qa openssh* openssh-7.4p1-21.el7.x86_64 openssh-clients-7.4p1-21.el7.x86_64 openssh-server-7.4p1-21.el7.x86_64-
服务器:/usr/sbin/sshd
-
Unit 文件:/usr/lib/systemd/system/sshd.service
-
客户端:
Linux Client: ssh, scp, (前两个常用)sftp,slogin(一般不用)
Windows Client:xshell, MobaXterm(常用)putty, securecrt, sshsecureshellclient
2.2.1 客户端ssh命令
ssh命令是ssh客户端,允许实现对远程系统经验证地加密安全访问
当用户远程连接ssh服务器时,会复制ssh服务器/etc/ssh/ssh_host*key.pub文件中的公钥到客户机的~./ssh/know_hosts中。下次连接时,会自动匹配相应私钥,不能匹配,将拒绝连接。
ssh客户端配置文件:/etc/ssh/ssh_config
主要配置:
[root@centos7 ~]# cat /etc/ssh/ssh_config #StrictHostKeyChecking ask #首次登录不显示检查提示 StrictHostKeyChecking no #在客户端的配置文件中改为no,首次登录不显示检查提示 # IdentityFile ~/.ssh/id_rsa # IdentityFile ~/.ssh/id_dsa # IdentityFile ~/.ssh/id_ecdsa # IdentityFile ~/.ssh/id_ed25519 # Port 22范例:禁止首次连接的询问过程
#未修改配置前,首次登录需要确认 [root@centos7 ~]# ssh 192.168.209.109 The authenticity of host '192.168.209.109 (192.168.209.109)' can't be established. ECDSA key fingerprint is SHA256:2qaHNgF3BS7kCF354+tbKFZTV/Xal+wjAegR++6GA84. ECDSA key fingerprint is MD5:b0:f5:03:f4:26:86:95:a7:83:dc:79:4e:8d:82:be:24. Are you sure you want to continue connecting (yes/no)? yes Warning: Permanently added '192.168.209.109' (ECDSA) to the list of known hosts. root@192.168.209.109's password: Last login: Thu May 6 02:24:49 2021 from 192.168.209.12 [root@centos8 ~]# exit logout Connection to 192.168.209.109 closed. #登录后,在客户端的.ssh目录中,会生成known_hosts文件,存放服务器的公钥 [root@centos7 ~]# cat .ssh/known_hosts 192.168.209.109 ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBMoAVPhnOjI1U1s1KWDVo6+HWjYs2x8K3TEed+r1+5I9/MGJi6K3dnKwlMn9TBVgoPsC+ij+e0aOc6851zHw7J0= #删除该文件,修改ssh_config配置文件,再次登录就没有确认提示信息了 [root@centos7 ~]# rm .ssh/known_hosts -f [root@centos7 ~]# sed -i.bak '/StrictHostKeyChecking/s/.*/StrictHostKeyChecking no/' /etc/ssh/ssh_config [root@centos7 ~]# ssh 192.168.209.109 Warning: Permanently added '192.168.209.109' (ECDSA) to the list of known hosts. root@192.168.209.109's password: Last login: Thu May 6 02:25:20 2021 from 192.168.209.12 [root@centos8 ~]#格式:
ssh [user@]host [COMMAND] ssh [-l user] host [COMMAND] [root@centos7 ~]# ssh 192.168.209.109 ##省略user,以当前用户身份登录远程主机 #以其他用户的身份登录,远程主机要有这个帐号才行,无该用户则无法登录 [root@centos7 ~]# ssh wang@192.168.209.109 wang@192.168.209.109's password: Last login: Thu May 6 02:34:20 2021 from 192.168.209.12 [wang@centos8 ~]$ exit logout Connection to 192.168.209.109 closed.范例:win10系统自带ssh命令,格式同上
C:\Users\Administrator>ssh 192.168.209.12 The authenticity of host '192.168.209.12 (192.168.209.12)' can't be established. ECDSA key fingerprint is SHA256:vrnNluWd5deVV+ZWi3011BVP+WeAo2xew+/7JiHqaKE. Are you sure you want to continue connecting (yes/no)? yes Warning: Permanently added '192.168.209.12' (ECDSA) to the list of known hosts. administrator@192.168.209.12's password: Permission denied, please try again. administrator@192.168.209.12's password: Permission denied, please try again. administrator@192.168.209.12's password: C:\Users\Administrator>ssh root@192.168.209.12 root@192.168.209.12's password: Last login: Mon May 3 15:13:31 2021 from 192.168.209.1 [root@centos7 ~]#ls anaconda-ks.cfg finish.log test.txt常见选项:
-p port #远程服务器监听的端口 -b #指定连接的源IP;指的是本地有多个ip地址时,指定一个ip地址连接 -v #调试模式,显示登录的详细过程 -C #压缩方式,节省带宽 -X #支持x11转发,跨网络显示图形界面,即本机打开的图形其实是服务器上的界面,如firefox浏览器等,类似win下的远程桌面 -t #强制伪tty分配,如:ssh -t remoteserver1 ssh -t remoteserver2 ssh remoteserver3 -o option #如:-o StrictHostKeyChecking=no -i <file> #指定私钥文件路径,实现基于key验证,默认使用文件: ~/.ssh/id_dsa, ~/.ssh/id_ecdsa, ~/.ssh/id_ed25519,~/.ssh/id_rsa等范例:-o选项
首次登录时不需要输入yes确认信息,只需输入密码登录即可,一是修改ssh_config配置文件,二是使用-o选项。
即ssh -o StrictHostKeyChecking=no 服务器IP
#首次连接远程服务器需要确认询问 [root@centos7 ~]#ssh 192.168.100.200 The authenticity of host '192.168.100.200 (192.168.100.200)' can't be established. ECDSA key fingerprint is SHA256:azJbbslqxN05PNFK9eveLOaMb7Ya9FMCaLOpTvuDU3s. ECDSA key fingerprint is MD5:60:c4:9d:91:2c:38:06:89:47:f9:89:1e:92:17:c3:a5. Are you sure you want to continue connecting (yes/no)? yes Warning: Permanently added '192.168.100.200' (ECDSA) to the list of known hosts. root@192.168.100.200's password: Last login: Wed May 5 10:43:08 2021 from 192.168.100.12 #连接后生成know_hosts文件,存储服务器的哈希值 [root@centos7 ~]#cat .ssh/known_hosts 192.168.100.200 ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBKiByO35pRcQ61ib2t7KaBzknSs8v94OQMAugj5XkozzMJDrfeA5VukJw/Uif+IxqwiMOZrjE/4uBAekRnaiAj8= #下次再登录不再询问 [root@centos7 ~]#ssh 192.168.100.200 root@192.168.100.200's password: #删除know_hosts文件,使用-o选项登录,不需要确认服务器身份,直接输入密码登录,并生成know_hosts文件 [root@centos7 ~]#rm .ssh/known_hosts -f [root@centos7 ~]#ssh 192.168.100.200 -o StrictHostKeyChecking=no Warning: Permanently added '192.168.100.200' (ECDSA) to the list of known hosts. root@192.168.100.200's password: Last login: Wed May 5 11:03:56 2021 from 192.168.100.12 [root@centos8 ~]# exit logout Connection to 192.168.100.200 closed. [root@centos7 ~]#cat .ssh/known_hosts 192.168.100.200 ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBKiByO35pRcQ61ib2t7KaBzknSs8v94OQMAugj5XkozzMJDrfeA5VukJw/Uif+IxqwiMOZrjE/4uBAekRnaiAj8= #也可以修改客户端的ssh_config配置文件,永久禁止首次连接询问 #sed -i.bak '/StrictHostKeyChecking/s/.*/StrictHostKeyChecking no/' /etc/ssh/ssh_config范例:-t选项
为了企业内部服务器的安全考虑,hostA只允许hostB的ssh连接,而hostB只允许hostC的ssh连接,hostC允许其他外部主机连接。怎么访问hostA主机呢常规方式是一级一级的ssh连接,比如先ssh登陆到C,再ssh到B,再ssh到C-t选项可以省略中间的步骤,即ssh -t hostC ssh -t hostB ssh hostA
[root@centos7 ~]# ssh -t 192.168.209.109 ssh -t 192.168.209.110 ssh 192.168.209.10 root@192.168.209.109's password: root@192.168.209.110's password: The authenticity of host '192.168.209.10 (192.168.209.10)' can't be established. ECDSA key fingerprint is SHA256:u60ZGqUbD13vW3Ngw3kVz2cPyHZ9s548BVQPdEdMRCs. Are you sure you want to continue connecting (yes/no/[fingerprint])? yes Warning: Permanently added '192.168.209.10' (ECDSA) to the list of known hosts. root@192.168.209.10's password: Last login: Thu May 6 16:15:45 2021 from 192.168.209.110 [root@repo-client ~]# exit logout Connection to 192.168.209.10 closed. Connection to 192.168.209.110 closed. Connection to 192.168.209.109 closed. [root@centos7 ~]#范例:远程执行命令
[root@centos7 ~]# ssh 192.168.209.109 hostname root@192.168.209.109's password: centos8.1 [root@centos7 ~]# ssh 192.168.209.109 hostname -I root@192.168.209.109's password: 192.168.209.109 #远程修改ssh_config配置文件 [root@centos7 ~]# ssh 192.168.209.109 sed -i.bak '/StrictHostKeyChecking/s/.*/StrictHostKeyChecking no/' /etc/ssh/ssh_config root@192.168.209.109's password: sed: -e expression #1, char 49: unterminated `s' command #命令太长,需要用""引起来 [root@centos7 ~]# ssh 192.168.209.109 "sed -i.bak '/StrictHostKeyChecking/s/.*/StrictHostKeyChecking no/' /etc/ssh/ssh_config" root@192.168.209.109's password: [root@centos7 ~]# [root@centos8 ~]# cat /etc/ssh/ssh_config |grep Strict StrictHostKeyChecking no [root@centos8 ~]# ll .ssh total 0 [root@centos8 ~]# ssh 192.168.209.110 Warning: Permanently added '192.168.209.110' (ECDSA) to the list of known hosts. root@192.168.209.110's password: Last login: Thu May 6 16:13:02 2021 from 192.168.209.109 [root@centos8110 ~]#范例:在远程主机运行本地shell脚本
[root@centos7 expect]#cat test.sh hostname -I [root@centos7 expect]#chmod +x test.sh [root@centos7 expect]#hostname -I 192.168.100.12 #远程执行test.sh脚本,查看服务器的ip地址 [root@centos7 expect]#ssh 192.168.100.200 /bin/bash </scripts/expect/test.sh root@192.168.100.200's password: 192.168.100.200 [root@centos7 expect]#范例:结合expect执行远程服务器上的命令
[root@centos8 scripts]# cat test_expect.sh #!/bin/bash NET=192.168.100 user=root password=magedu rpm -q expect || yum install -y expect for ID in 7 18 17;do ip=$NET.$ID expect <<EOF set timeout 20 spawn ssh $user@$ip hostname -I expect { "yes/no" { send "yes\n";exp_continue } "password" { send "$password\n" } } #expect "#" { send "/bin/bash </scripts/test.sh\n" } #expect "#" { send "exit\n" } expect eof EOF done [root@centos8 scripts]# bash test_expect.sh expect-5.45.4-5.el8.x86_64 spawn ssh root@192.168.100.7 hostname -I root@192.168.100.7's password: 192.168.100.7 spawn ssh root@192.168.100.18 hostname -I root@192.168.100.18's password: 192.168.100.18 spawn ssh root@192.168.100.17 hostname -I root@192.168.100.17's password: 192.168.100.172.2.2 ssh登录验证方式介绍
ssh服务登录的常用验证方式
- 用户/口令:需要人机交互,密码容易泄露,不安全
- 基于密钥
基于用户和口令登录验证
基于密钥的登录方式
2.2.3 实现基于密钥的登录方式
在客户端生成密钥对
ssh-keygen -t rsa [-P 'password'] [-f “~/.ssh/id_rsa"]把公钥文件传输至远程服务器对应用户的家目录
ssh-copy-id [-i [identity_file]] [user@]host重设私钥口令:
ssh-keygen –p验证代理(authentication agent)保密解密后的密钥,口令就只需要输入一次,在GNOME中,代理被自动提供给root用户
#启用代理 ssh-agent bash #钥匙通过命令添加给代理 ssh-add范例:实现基于 key 验证
#3台主机实验,centos7(100.12)、centos8(100.200)、c7-test(100.11) #先删除这3台主机中的.ssh目录及文件 [root@c7-test ~]# rm .ssh -rf [root@centos8 ~]#rm .ssh -rf [root@centos7 ~]#rm .ssh -rf #生成客户端的公钥和私钥 [root@centos7 ~]#ssh-keygen Generating public/private rsa key pair. Enter file in which to save the key (/root/.ssh/id_rsa): #回车,接受默认值 Created directory '/root/.ssh'. #回车后,创建了.ssh目录 Enter passphrase (empty for no passphrase): #回车,接受默认值,空密码 Enter same passphrase again: #回车,接受默认值 Your identification has been saved in /root/.ssh/id_rsa. Your public key has been saved in /root/.ssh/id_rsa.pub. The key fingerprint is: SHA256:KGGrKfaKRSSK8XX/AwQcd9GC3RSUo6VL9Kw2EctvtQE root@centos7 The key's randomart image is: +---[RSA 2048]----+ | .o..oo*+o | | .o..= E | |o . + . .o X o | |o= o + + B o o | |o o o . S. = . o | | . o . o= o . | |..+ .oo | |oo. . | |.... | +----[SHA256]-----+ #查看公钥私钥 [root@centos7 ~]#ll .ssh -rw------- 1 root root 1679 May 5 15:48 id_rsa -rw-r--r-- 1 root root 394 May 5 15:48 id_rsa.pub [root@centos7 ~]#cat .ssh/id_rsa #私钥 -----BEGIN RSA PRIVATE KEY----- -----END RSA PRIVATE KEY----- #公钥 [root@centos7 ~]#cat .ssh/id_rsa.pub ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCidCy42Zlytgo7MNiZOmjc9c2gBeIgGv0I3RLzRZP82O1CMHrJw6W5X0u+PYiWaphxFojuuSRyQf7IO2uaxtNf7f2iwUBn5Ikko5NspYuslSPL1sszmiIt2kIQLm//KOm5+Rn/rIMmcX52MPJt7v0WjSJlqRRnntnetwy7fdxmRMDD9npEiAgbSP6GKO+gGQ3fQUK5Gf25/WlovdRTWCdg/JX+KX0WkiPSK062337/gDbBWptCCZ/B2gCySGK54T0PS1IGwxBVBOKqfpKe0SpVOzs9zOHNri07ln7U9U5kayrI4BFec93rmjQ8TY/c5GAGhM1OFuLm7F4EtiQYJhfp root@centos7 #复制公钥到centos8主机,user可以省略,以当前用户登录 [root@centos7 ~]#ssh-copy-id root@192.168.100.200 /usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub" The authenticity of host '192.168.100.200 (192.168.100.200)' can't be established. ECDSA key fingerprint is SHA256:azJbbslqxN05PNFK9eveLOaMb7Ya9FMCaLOpTvuDU3s. ECDSA key fingerprint is MD5:60:c4:9d:91:2c:38:06:89:47:f9:89:1e:92:17:c3:a5. Are you sure you want to continue connecting (yes/no)? yes /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@192.168.100.200's password: Number of key(s) added: 1 Now try logging into the machine, with: "ssh 'root@192.168.100.200'" and check to make sure that only the key(s) you wanted were added. #查看centos8上刚刚复制过来的centos7客户端的公钥 [root@centos8 ~]# ll .ssh total 4 -rw------- 1 root root 394 May 5 15:49 authorized_keys [root@centos8 ~]# cat .ssh/authorized_keys ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCidCy42Zlytgo7MNiZOmjc9c2gBeIgGv0I3RLzRZP82O1CMHrJw6W5X0u+PYiWaphxFojuuSRyQf7IO2uaxtNf7f2iwUBn5Ikko5NspYuslSPL1sszmiIt2kIQLm//KOm5+Rn/rIMmcX52MPJt7v0WjSJlqRRnntnetwy7fdxmRMDD9npEiAgbSP6GKO+gGQ3fQUK5Gf25/WlovdRTWCdg/JX+KX0WkiPSK062337/gDbBWptCCZ/B2gCySGK54T0PS1IGwxBVBOKqfpKe0SpVOzs9zOHNri07ln7U9U5kayrI4BFec93rmjQ8TY/c5GAGhM1OFuLm7F4EtiQYJhfp root@centos7 #再次连接c8,不用输入密码,即可连接 [root@centos7 ~]#ssh 192.168.100.200 Last login: Wed May 5 15:46:53 2021 from 192.168.100.12 #假如复制公钥时,误把私钥文件复制到了服务器上,会出现什么情况 #复制私钥到c7-test服务器上 [root@centos7 ~]#ssh-copy-id -i .ssh/id_rsa 192.168.100.11 /usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: ".ssh/id_rsa.pub" The authenticity of host '192.168.100.11 (192.168.100.11)' can't be established. ECDSA key fingerprint is SHA256:LsADkBrAATQSCqxKP9lZXDYm2WncbAvsH3M1Z0ubNpE. ECDSA key fingerprint is MD5:5c:bf:b4:5d:6a:24:38:4e:1c:1e:47:d0:b9:92:c2:08. Are you sure you want to continue connecting (yes/no)? yes /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@192.168.100.11's password: Number of key(s) added: 1 Now try logging into the machine, with: "ssh '192.168.100.11'" and check to make sure that only the key(s) you wanted were added. #查看c7-test服务器上的文件,发现即使写的是私钥的文件名,复制过来的还是公钥信息。 [root@c7-test ~]# ll .ssh total 4 -rw------- 1 root root 394 May 5 15:54 authorized_keys [root@c7-test ~]# cat .ssh/authorized_keys ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCidCy42Zlytgo7MNiZOmjc9c2gBeIgGv0I3RLzRZP82O1CMHrJw6W5X0u+PYiWaphxFojuuSRyQf7IO2uaxtNf7f2iwUBn5Ikko5NspYuslSPL1sszmiIt2kIQLm//KOm5+Rn/rIMmcX52MPJt7v0WjSJlqRRnntnetwy7fdxmRMDD9npEiAgbSP6GKO+gGQ3fQUK5Gf25/WlovdRTWCdg/JX+KX0WkiPSK062337/gDbBWptCCZ/B2gCySGK54T0PS1IGwxBVBOKqfpKe0SpVOzs9zOHNri07ln7U9U5kayrI4BFec93rmjQ8TY/c5GAGhM1OFuLm7F4EtiQYJhfp root@centos7 [root@centos7 ~]#ssh 192.168.100.11 Last login: Wed May 5 15:47:39 2021 from 192.168.100.12centos7的私钥被复制到其他客户端上,同样可以免密登录centos8(100.200)和c7-test(100.11)这两台服务器,一定要保护好私钥。
#实验,复制私钥到其他客户端(100.13),实现免密登录服务器 #1、首先13上先创建.ssh目录 [root@centos7-http ~]# mkdir .ssh #2、复制私钥到13的.ssh目录中 [root@centos7 ~]#scp -p .ssh/id_rsa 192.168.100.13:/root/.ssh/ root@192.168.100.13's password: id_rsa 100% 1679 681.8KB/s 00:00 [root@centos7 ~]# #3、查看.ssh目录中的私钥文件 [root@centos7-http ~]# ll .ssh total 4 -rw------- 1 root root 1679 May 5 15:48 id_rsa #4、远程登录服务器,也不需要输入密码 [root@centos7-http ~]# ssh 192.168.100.200 Last login: Wed May 5 16:43:02 2021 from 192.168.100.13 [root@centos8 ~]#所以,需要给私钥加密码,之前申请私钥公钥对时,默认是空密码
#可以在创建私钥时加密码,也可以生成私钥以后,再添加密码 #给私钥添加密码 [root@centos7 ~]#ssh-keygen -p Enter file in which the key is (/root/.ssh/id_rsa): Enter new passphrase (empty for no passphrase): Enter same passphrase again: Your identification has been saved with the new passphrase. #登录的时候,需输入私钥的密码才能登录 [root@centos7 ~]#ssh 192.168.100.200 Enter passphrase for key '/root/.ssh/id_rsa': #输入私钥的密码 Last login: Wed May 5 16:51:13 2021 from 192.168.100.13 [root@centos8 ~]#但每次连接服务器时,还需输入私钥的密码,要实现非交互方式,需要使用ssh-agent,一旦退出远程连接,就停止运行,很安全的保护了ssh连接。需要使用密钥登录时,使用一次ssh-agent,使用后,exit退出即可。
[root@centos7 ~]#ps aux|grep agent root 5699 0.0 0.0 112812 972 pts/2 S+ 16:55 0:00 grep --color=auto agent #启用ssh-agent代理 [root@centos7 ~]#ssh-agent bash [root@centos7 ~]#ps aux|grep agent root 5701 0.0 0.0 72508 780 ? Ss 16:55 0:00 ssh-agent bash root 5721 0.0 0.0 112812 976 pts/2 S+ 16:56 0:00 grep --color=auto agent #加入私钥密码,登录服务器时,就不会提示私钥密码了 [root@centos7 ~]#ssh-add Enter passphrase for /root/.ssh/id_rsa: #输入私钥密码 Identity added: /root/.ssh/id_rsa (/root/.ssh/id_rsa) [root@centos7 ~]#ssh 192.168.100.200 Last login: Wed May 5 16:51:44 2021 from 192.168.100.12 [root@centos8 ~]# exit logout Connection to 192.168.100.200 closed. [root@centos7 ~]#exit #只要退出两次,无论进程里有没有ssh-agent,登录服务器时都需要输入私钥密码 exit [root@centos7 ~]#ps aux|grep agent root 5804 0.0 0.0 112812 976 pts/2 S+ 17:03 0:00 grep --color=auto agent2.2.3.1 多台服务器配置ssh连接
多台服务器,需要配置ssh连接,执行初始化脚本,就要用循环的方式来执行
#以两台主机为例,初始化ip地址文件host.txt以及执行的脚本文件test.sh [root@centos7 ~]#cat /scripts/expect/host.txt 192.168.100.200 192.168.100.11 [root@centos7 ~]#cat /scripts/expect/test.sh echo The host '"'`hostname`'"' ipaddress is $(hostname -I) #使用ssh连接,批量执行脚本 [root@centos7 ~]#while read ip;do ssh $ip bash </scripts/expect/test.sh;done </scripts/expect/host.txt The host "centos8" ipaddress is 192.168.100.200 The host "c7-test" ipaddress is 192.168.100.11 [root@centos7 ~]# #使用ssh连接,在远程服务器上批量创建用户 [root@centos7 ~]#while read ip;do ssh $ip useradd hihi ;done </scripts/expect/host.txt [root@centos8 ~]# getent passwd|grep hihi hihi:x:1002:1002::/home/hihi:/bin/bash [root@c7-test ~]# getent passwd |grep hihi #而最后一台主机(100.11)没有创建hihi用户,说明host.txt文件的最后一行没有执行,改成for循环,就可以执行用户的创建了 [root@centos7 ~]#for i in `cat /scripts/expect/host.txt`;do ssh $i useradd haha ;done [root@centos8 ~]# getent passwd|grep haha haha:x:1003:1003::/home/haha:/bin/bash [root@c7-test ~]# getent passwd |grep haha haha:x:1002:1002::/home/haha:/bin/bash范例:expect实现批量基于ssh的key部署
[root@centos7 scripts]#cat push_ssh_key.sh #!/bin/bash PASS=magedu rpm -q expect &> /dev/null || yum -y install expect &> /dev/null ssh-keygen -t rsa -P "" -f /root/.ssh/id_rsa &> /dev/null && echo "ssh key is created" while read IP ;do expect &> /dev/null <<EOF #或者expect <<EOF &> /dev/null set timeout 20 spawn ssh-copy-id -i /root/.ssh/id_rsa.pub root@$IP expect { "yes/no" { send "yes\n";exp_continue } "password" { send "$PASS\n" } } expect eof EOF echo $IP is ready done < hosts.txt [root@centos7 scripts]#cat hosts.txt 192.168.100.13 192.168.100.200 [root@centos7 scripts]#bash push_ssh_key.sh ssh key is created 192.168.100.13 is ready 192.168.100.200 is ready [root@centos7 scripts]#ssh 192.168.100.200 Last login: Thu May 6 20:58:59 2021 from 192.168.100.12 [root@centos8 ~]# exit logout Connection to 192.168.100.200 closed. [root@centos7 scripts]#ssh 192.168.100.13 Last login: Thu May 6 20:58:37 2021 from 192.168.100.12 [root@centos7-http ~]# exit logout Connection to 192.168.100.13 closed. [root@centos7 scripts]#2.2.4 其它ssh客户端工具
2.2.4.1 scp命令
跨网络通信,主机之间传输数据,使用ssh协议
scp [options] SRC... DEST/两种方式:
scp [options] [user@]host:/sourcefile /destpath scp [options] /sourcefile [user@]host:/destpath scp -r /data/ 192.168.100.200:/tmp #把本地的/data目录到远程主机的tmp目录下 scp /data/* 192.168.100.200:/tmp #把本地的/data目录下的文件复制到远程tmp下常用选项:
-C #压缩数据流 -r #递归复制 -p #保持原文件的属性信息 -q #静默模式 -P PORT #指明remote host的监听的端口注意:scp复制文件时,不会考虑文件是否相同,而是全部复制;当生成中文件非常大时,就需要使用增量复制的方式,就要使用rsync命令
2.2.4.2 rsync 命令
rsync工具可以基于ssh和rsync协议实现高效率的远程系统之间复制文件,使用安全的shell连接做为传输方式,比scp更快,基于增量数据同步,即只复制两方不同的文件,此工具来自于rsync包注意:通信两端主机都需要安装 rsync软件
rsync -av /etc server1:/tmp #复制目录和目录下文件,不加/ rsync -av /etc/ server1:/tmp #只复制目录下文件,加/常用选项:
-n #模拟复制过程 -v #显示详细过程 -r #递归复制目录树 -p #保留权限 -t #保留修改时间戳 -g #保留组信息 -o #保留所有者信息 -l #将软链接文件本身进行复制(默认) -L #将软链接文件指向的文件复制 -u #如果接收者的文件比发送者的文件较新,将忽略同步 -z #压缩,节约网络带宽 -a #存档,相当于–rlptgoD,但不保留ACL(-A)和SELinux属性(-X) --delete #源数据删除,目标数据也自动同步删除范例:
[root@centos8 ~]#rsync -auv --delete /data/test 10.0.0.7:/data范例:-a、-u、--delete选项
#双方主机都要安装rsync服务,否则会报错 [root@centos7 data]#rsync -av /data/f*.img 192.168.100.200:/test bash: rsync: command not found rsync: connection unexpectedly closed (0 bytes received so far) [sender] rsync error: remote command not found (code 127) at io.c(226) [sender=3.1.2] #准备测试文件 [root@centos7 data]#dd if=/dev/zero of=/data/f1.img bs=1M count=100 100+0 records in 100+0 records out 104857600 bytes (105 MB) copied, 0.117882 s, 890 MB/s [root@centos7 data]#dd if=/dev/zero of=/data/f2.img bs=1M count=100 100+0 records in 100+0 records out 104857600 bytes (105 MB) copied, 0.125478 s, 836 MB/s [root@centos7 data]#dd if=/dev/zero of=/data/f3.img bs=1M count=100 100+0 records in 100+0 records out 104857600 bytes (105 MB) copied, 0.13133 s, 798 MB/s [root@centos7 data]#ll f*.img -rw-r--r-- 1 root root 104857600 May 5 18:54 f1.img -rw-r--r-- 1 root root 104857600 May 5 18:54 f2.img -rw-r--r-- 1 root root 104857600 May 5 18:54 f3.img #复制文件到远程主机100.200的test目录中 [root@centos7 data]#rsync -av /data/f*.img 192.168.100.200:/test sending incremental file list f1.img f2.img f3.img sent 314,649,805 bytes received 73 bytes 29,966,655.05 bytes/sec total size is 314,572,800 speedup is 1.00 [root@centos8 ~]# ll /test total 307200 -rw-r--r-- 1 root root 104857600 May 5 18:54 f1.img -rw-r--r-- 1 root root 104857600 May 5 18:54 f2.img -rw-r--r-- 1 root root 104857600 May 5 18:54 f3.img #1、-av #修改f1.img文件,那么使用rsync复制时,只复制f1这个文件 [root@centos7 data]#echo hello >>f1.img [root@centos7 data]#ll f*.img -rw-r--r-- 1 root root 104857606 May 5 18:58 f1.img -rw-r--r-- 1 root root 104857600 May 5 18:54 f2.img -rw-r--r-- 1 root root 104857600 May 5 18:54 f3.img [root@centos7 data]#rsync -av /data/f*.img 192.168.100.200:/test sending incremental file list f1.img sent 41,102 bytes received 71,719 bytes 45,128.40 bytes/sec total size is 314,572,806 speedup is 2,788.25 [root@centos8 ~]# ll /test total 307204 -rw-r--r-- 1 root root 104857606 May 5 18:58 f1.img -rw-r--r-- 1 root root 104857600 May 5 18:54 f2.img -rw-r--r-- 1 root root 104857600 May 5 18:54 f3.img #2、-u #如果服务器200上的文件较新,-av选项会覆盖该文件,而加上-u选项,就不会覆盖该文件 #更新f2.img文件 [root@centos8 ~]# echo >> /test/f2.img [root@centos8 ~]# ll /test total 307208 -rw-r--r-- 1 root root 104857606 May 5 18:58 f1.img -rw-r--r-- 1 root root 104857601 May 5 19:02 f2.img -rw-r--r-- 1 root root 104857600 May 5 18:54 f3.img #复制时,会覆盖f2.img文件 [root@centos7 data]#rsync -av /data/f*.img 192.168.100.200:/test sending incremental file list f2.img sent 41,092 bytes received 71,726 bytes 45,127.20 bytes/sec total size is 314,572,806 speedup is 2,788.32 #而更新f3.img文件后,并且创建f4.img文件 [root@centos8 ~]# echo >> /test/f3.img [root@centos8 ~]# touch /test/f4.img [root@centos8 ~]# ll /test total 438276 -rw-r--r-- 1 root root 104857606 May 5 18:58 f1.img -rw-r--r-- 1 root root 104857600 May 5 18:54 f2.img -rw-r--r-- 1 root root 104857601 May 5 19:03 f3.img -rw-r--r-- 1 root root 0 May 5 19:05 f4.img #加上-u选项,就不会覆盖f3,也不会删除f4 [root@centos7 data]#rsync -auv /data/f*.img 192.168.100.200:/test sending incremental file list sent 89 bytes received 12 bytes 67.33 bytes/sec total size is 314,572,806 speedup is 3,114,582.24 #3、--delete #目录同步,即客户端目录中的文件和服务器端始终保持同步,客户端删除文件,服务端也同样删除,并且有不在客户端的文件也会一并删除 #客户端删除f1,并修改f3.img文件内容 [root@centos7 data]#rm f1.img -f [root@centos7 data]#ls f2.img f3.img [root@centos7 data]#cat f3.img hello #服务端创建f4,并修改f2的内容 [root@centos8 ~]# echo >> /test/f2.img [root@centos8 ~]# ll /test total 438272 -rw-r--r-- 1 root root 104857600 May 5 18:54 f1.img -rw-r--r-- 1 root root 104857601 May 5 19:21 f2.img -rw-r--r-- 1 root root 104857600 May 5 18:54 f3.img -rw-r--r-- 1 root root 0 May 5 19:15 f4.img #-av --delete可以保证客户端和服务器端文件始终保持一致 [root@centos7 data]#rsync -av --delete /data/test/data/ 192.168.100.200:/test sending incremental file list deleting f4.img #删除了客户端中没有的f4和f1文件,并更新了f3 deleting f1.img ./ f3.img sent 152 bytes received 71,749 bytes 47,934.00 bytes/sec total size is 104,857,606 speedup is 1,458.36 [root@centos8 ~]# ll /test total 102404 -rw-r--r-- 1 root root 104857600 May 5 18:54 f2.img #f2恢复正常 -rw-r--r-- 1 root root 6 May 5 19:22 f3.img #f3内容也更新了3 ssh服务器配置
服务器端:sshd
服务器端的配置文件: /etc/ssh/sshd_config
客户端的配置文件:/etc/ssh/ssh_config
服务器端的配置文件帮助:man 5 sshd_config
常用参数:
Port #端口号,默认22,需要更改 ListenAddress ip #比如两个ip,一个外网,一个内网;绑定内网地址,外网就不能登录了,保证服务器安全 HostKey /etc/ssh/ssh_host_rsa_key HostKey /etc/ssh/ssh_host_ecdsa_key HostKey /etc/ssh/ssh_host_ed25519_key #公钥私钥路径 LoginGraceTime 2m #宽限期,2分钟后断开连接 PermitRootLogin yes #root登录权限,默认ubuntu不允许root远程ssh登录 StrictModes yes #检查.ssh/文件的所有者,权限等 MaxAuthTries 6 #尝试连接错误的次数,指定数值的一半,默认是6,次数就是3次 MaxSessions 10 #同一个连接最大会话(一个连接复制10个窗口,就是10个会话) PubkeyAuthentication yes #基于key验证 PermitEmptyPasswords no #空密码连接 PasswordAuthentication yes #基于用户名和密码连接 GatewayPorts no #是否启用网关 ClientAliveInterval 10 #活跃间隔,单位:秒 ClientAliveCountMax 3 #最大次数,默认3;连续检查3次,每次10秒,不活跃,就断开 UseDNS yes #dns反向解析,提高速度可改为no GSSAPIAuthentication yes #提高速度可改为no MaxStartups #未经认证连接最大值,默认值10 Banner /path/file #显示连接时的提示信息或欢迎词,放在file文件中 #以下可以限制可登录用户的办法: #见”Linux限制某些用户或IP登录SSH、允许特定IP登录SSH.md"文件 AllowUsers user1 user2 user3 DenyUsers AllowGroups DenyGroups范例:设置ssh 空闲60s 自动注销
[root@centos8 ~]# Vim /etc/ssh/sshd_config ClientAliveInterval 60 ClientAliveCountMax 0 [root@centos8 ~]# systemctl restart sshd #注意:新开一个连接才有效 #测试,新开一个连接 [root@centos7 ~]# ssh 192.168.209.109 root@192.168.209.109's password: Last login: Thu May 6 21:15:16 2021 from 192.168.209.12 [root@centos8 ~]# Connection to 192.168.209.109 closed by remote host. Connection to 192.168.209.109 closed. [root@centos7 ~]#范例:解决ssh登录缓慢的问题
[root@centos7 ~]#vim /etc/ssh/sshd_config UseDNS no GSSAPIAuthentication no #或使用sed修改 [root@centos8 ~]# sed -i.bak '/^#UseDNS/s/.*/UseDNS no/' /etc/ssh/sshd_config [root@centos8 ~]# sed -i.bak '/GSSAPIAuthentication/s/.*/GSSAPIAuthentication no/' /etc/ssh/sshd_config [root@centos8 ~]#systemctl restart sshdssh服务的最佳实践:
- 建议使用非默认端口
- 禁止使用protocol version 1
- 限制可登录用户,建立黑白名单
- 设定空闲会话超时时长
- 利用防火墙设置ssh访问策略
- 仅监听特定的IP地址,如只允许内网ip连接
- 基于口令认证时,为防止泄露,可使用强密码策略,比如:设置随机口令tr -dc A-Za-z0-9_ < /dev/urandom | head -c 12|xargs
- 使用基于密钥的认证
- 禁止使用空密码
- 禁止root用户直接登录
- 限制ssh的访问频度和并发在线数
- 经常分析日志
3.1 ssh 其它相关工具
3.1.1 挂载远程ssh目录 sshfs
由EPEL源提供,可以利用ssh协议挂载远程目录(目前CentOS8 还没有提供安装包)
[root@centos7 ~]#yum install fuse-sshfs [root@centos7 ~]#mkdir /testmp [root@centos7 ~]#sshfs 192.168.100.200:/test /testmp [root@centos7 ~]#mount |grep testmp 192.168.100.200:/test on /testmp type fuse.sshfs (rw,nosuid,nodev,relatime,user_id=0,group_id=0) [root@centos7 ~]#df /testmp Filesystem 1K-blocks Used Available Use% Mounted on 192.168.100.200:/test 18855936 14293348 4562588 76% /testmp [root@centos7 ~]#touch /testmp/centos7.txt [root@centos8 test]# ll total 0 -rw-r--r-- 1 root root 0 May 6 22:03 centos7.txt3.1.2 自动登录ssh工具sshpass
由EPEL源提供,ssh登陆不能在命令行中指定密码。sshpass的出现,解决了这一问题。sshpass用于非交互SSH的密码验证,一般用在sh脚本中,无须再次输入密码(本机known_hosts文件中有的主机才能生效)。它允许你用 -p 参数指定明文密码,然后直接登录远程服务器,它支持密码从命令行、文件、环境变量中读取。
格式:
sshpass [option] command parameters常见选项:
-p password #后跟密码它允许你用 -p 参数指定明文密码,然后直接登录远程服务器 -f filename #后跟保存密码的文件名,密码是文件内容的第一行。 -e #将环境变量SSHPASS作为密码范例:
[root@centos8 ~]#yum -y install sshpass #sshpass -p+password第一次连接服务器时,遇到输入yes/no会登录失败,所以需要加上-o StrictHostKeyChecking=no选项 1、-p选项 #第一次登录100.200主机,虽然没有任何提示,但没有登录成功 [root@centos7 ~]#sshpass -p magedu ssh 192.168.100.200 #ssh加上-o StrictHostKeyChecking=no选项,就能直接登录 [root@centos7 ~]#sshpass -p magedu ssh -o StrictHostKeyChecking=no 192.168.100.200 Warning: Permanently added '192.168.100.200' (ECDSA) to the list of known hosts. Last login: Thu May 6 21:59:43 2021 from 192.168.100.1 [root@centos8 ~]# #登录远程主机执行命令 [root@centos7 ~]#sshpass -p magedu ssh -o StrictHostKeyChecking=no 192.168.100.200 hostname -I 192.168.100.200 [root@centos7 ~]#sshpass -p magedu ssh -o StrictHostKeyChecking=no 192.168.100.13 bash </scripts/expect/test.sh The host "centos7-http" ipaddress is 192.168.100.13 #但这样操作,会在history中留下密码的记录,不安全 [root@centos7 ~]#history 1047 sshpass -p magedu ssh -o StrictHostKeyChecking=no 192.168.100.200 1048 sshpass -p magedu ssh -o StrictHostKeyChecking=no 192.168.100.200 hostname -I 2、-f选项 #把密码放在file文件中,并把权限改为600 [root@centos7 ~]#cat pass.txt magedu [root@centos7 ~]#chmod 600 pass.txt [root@centos7 ~]#ll pass.txt -rw------- 1 root root 7 May 6 22:26 pass.txt [root@centos7 ~]#sshpass -f pass.txt ssh -o StrictHostKeyChecking=no 192.168.100.200 hostname centos8 [root@centos7 ~]#history #只能看到文件名,看不到密码 1059 sshpass -f pass.txt ssh -o StrictHostKeyChecking=no 192.168.100.200 hostname 3、-e选项 #放在SSHPASS变量里,必须大写 [root@centos7 ~]#export SSHPASS=magedu [root@centos7 ~]#sshpass -e ssh -o StrictHostKeyChecking=no 192.168.100.200 hostname centos8范例:批量修改多台主机的root密码为随机密码
#ip地址在一个网段内,可以使用循环来调用 [root@centos7 scripts]#cat change_root_password.sh #!/bin/bash rpm -q sshpass &> /dev/null || yum -y install sshpass export SSHPASS=magedu NET=10.0.0 for i in {1..254};do { PASS=`openssl rand -base64 9` sshpass -e ssh $NET.$i "echo $PASS|passwd --stdin root &> /dev/null" echo $NET.$i:$PASS >> host.txt }& done wait #ip地址随机,不连续,可以放在文件中,调用即可 [root@centos7 scripts]#cat change_root_pass.sh #!/bin/bash HOST=" 192.168.100.200 192.168.100.13 " rpm -q sshpass &> /dev/null || yum -y install sshpass export SSHPASS=magedu for i in $HOST;do { PASS=`openssl rand -base64 9` sshpass -e ssh -o StrictHostKeyChecking=no $i "echo $PASS|passwd --stdin root &> /dev/null" echo $i:$PASS >> host.txt }& done wait #测试 [root@centos7 scripts]#bash change_root_pass.sh Warning: Permanently added '192.168.100.200' (ECDSA) to the list of known hosts. Warning: Permanently added '192.168.100.13' (ECDSA) to the list of known hosts. Changing password for user root. passwd: all authentication tokens updated successfully. Changing password for user root. passwd: all authentication tokens updated successfully. [root@centos7 scripts]#cat host.txt 192.168.100.13:VyRbdFW7BqRe 192.168.100.200:PShWHu8+WyWx范例:批量部署多台主机基于key验证脚本
#ip地址随机,不连续,可以放在文件中,调用即可 [root@centos7 scripts]# cat sshpass_autokey.sh #!/bin/bash HOST=" 192.168.209.10 192.168.209.109 " PASS=magedu ssh-keygen -P "" -f /root/.ssh/id_rsa &> /dev/null rpm -q sshpass &>/dev/null || yum -y install sshpass &> /dev/null for i in $HOST;do { sshpass -p $PASS ssh-copy-id -o StrictHostKeyChecking=no -i /root/.ssh/id_rsa.pub $i &>/dev/null }& done wait [root@centos7 scripts]# bash sshpass_autokey.sh [root@centos7 scripts]# ssh 192.168.209.109 Last login: Thu May 6 22:20:00 2021 from 192.168.209.12 [root@centos8 ~]#3.1.3 轻量级自动化运维工具 pssh
EPEL源中提供了多个自动化运维工具
pssh:基于python编写,可在多台服务器上执行命令的工具,也可实现文件复制,提供了基于ssh和scp的多个并行工具,链接地址:http://code.google.com/p/parallel-ssh/, CentOS8上目前没提供
pdsh:Parallel remote shell program,是一个多线程远程shell客户端,可以并行执行多个远程主机上的命令。 可使用几种不同的远程shell服务,包括rsh,Kerberos IV和ssh,地址: https://pdsh.googlecode.com/
mussh:Multihost SSH wrapper,是一个shell脚本,允许使用命令在多个主机上通过ssh执行命令。 可使用ssh-agent和RSA/DSA密钥,以减少输入密码,地址:http://www.sourceforge.net/projects/mussh
3.1.3.1 pssh 命令
常用选项:
-H #主机字符串,内容格式”[user@]host[:port]” -h file #主机列表文件,内容格式”[user@]host[:port]” -A #手动输入密码模式 -i #每个服务器内部处理信息输出 -l #登录使用的用户名 -p #并发的线程数【可选】 -o #输出的文件目录【可选】 -e #错误输出文件【可选】 -t TIMEOUT #超时时间设置,0无限制【可选】 -O #SSH的选项 -P #打印出服务器返回信息 -v #详细模式 --version #查看版本范例:
[root@centos7 scripts]# yum -y install pssh [root@centos7 scripts]# rpm -ql pssh /usr/bin/pnuke /usr/bin/prsync /usr/bin/pscp.pssh /usr/bin/pslurp /usr/bin/pssh 1、-H -A -i 选项 #默认使用ssh的key认证,如果没有事先认证,需要加-A选项,输入密码后执行 [root@centos7 ~]# ssh 192.168.209.10 #无key验证 root@192.168.209.10's password: [root@centos7 ~]# pssh -H 192.168.209.10 hostname #错误提示 [1] 10:57:56 [FAILURE] 192.168.209.10 Exited with error code 255 [root@centos7 scripts]# pssh -H 192.168.209.10 -A -i hostname Warning: do not enter your password if anyone else has superuser privileges or access to your account. Password: [1] 11:03:31 [SUCCESS] 192.168.209.10 c7-client #多个主机执行命令时,需要加""引起来,并且密码一样才行 [root@centos7 scripts]# pssh -H "192.168.209.10 192.168.209.109" -A -i hostname Password: [1] 11:07:28 [SUCCESS] 192.168.209.10 c7-client [2] 11:07:28 [SUCCESS] 192.168.209.109 centos8.1 #密码不同,哪个密码正确,显示哪台主机的信息 [root@centos7 scripts]# pssh -H "192.168.209.10 192.168.209.109" -A -i hostname Password: #此时输入的是109的主机密码 [1] 11:10:26 [SUCCESS] 192.168.209.109 centos8.1 [2] 11:10:28 [FAILURE] 192.168.209.10 Exited with error code 255 Stderr: Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password). #要实现不输入密码执行命令,需要执行上面的sshpass_autokey.sh脚本,实现key验证 [root@centos7 scripts]# bash sshpass_autokey.sh cp id_rsa.pub ok cp id_rsa.pub ok #就可以直接执行命令 [root@centos7 scripts]# pssh -H 192.168.209.10 hostname [1] 10:59:12 [SUCCESS] 192.168.209.10 [root@centos7 scripts]# pssh -H 192.168.209.10 -i hostname [1] 10:59:21 [SUCCESS] 192.168.209.10 c7-client #加上用户执行,每个ip都要加,而且用户的密码也要一致 [root@centos7 scripts]# pssh -H wang@"192.168.209.10 192.168.209.109" -A -i hostname Warning: do not enter your password if anyone else has superuser privileges or access to your account. Password: [1] 11:15:47 [SUCCESS] wang@192.168.209.10 c7-client [2] 11:15:50 [FAILURE] 192.168.209.109 Exited with error code 255 Stderr: Permission denied (publickey,password). [root@centos7 scripts]# pssh -H "wang@192.168.209.10 wang@192.168.209.109" -A -i hostname Warning: do not enter your password if anyone else has superuser privileges or access to your account. Password: [1] 11:20:55 [SUCCESS] wang@192.168.209.10 c7-client [2] 11:20:56 [SUCCESS] wang@192.168.209.109 centos8.1 #通过pssh批量关闭seLinux [root@centos7 scripts]# pssh -H "192.168.209.10 192.168.209.109" -i sed -i 's/SELINUX=.*/SELINUX=disabled/' /etc/selinux/config [1] 11:25:13 [SUCCESS] 192.168.209.10 [2] 11:25:14 [SUCCESS] 192.168.209.109 2、-h file #把主机ip放在file中,使用-h调用 [root@centos7 scripts]# cat hosts.txt 192.168.209.10 192.168.209.109 [root@centos7 scripts]# pssh -h host.txt -i hostname [1] 11:34:03 [SUCCESS] 192.168.209.109 centos8.1 [2] 11:34:03 [SUCCESS] 192.168.209.10 c7-client #调用主机ip,创建用户 [root@centos7 scripts]# pssh -h host.txt -i useradd tomcat [1] 12:54:28 [SUCCESS] 192.168.209.10 [2] 12:54:30 [SUCCESS] 192.168.209.109 [root@centos7 scripts]# pssh -h host.txt -i getent passwd tomcat [1] 12:55:53 [SUCCESS] 192.168.209.10 tomcat:x:1002:1002::/home/tomcat:/bin/bash [2] 12:55:54 [SUCCESS] 192.168.209.109 tomcat:x:1001:1001::/home/tomcat:/bin/bash #创建文件,目录要存在 [root@centos7 scripts]# pssh -h host.txt -i touch /data/test.txt [1] 12:56:50 [FAILURE] 192.168.209.10 Exited with error code 1 Stderr: touch: cannot touch ‘/data/test.txt’: No such file or directory [2] 12:56:51 [SUCCESS] 192.168.209.109 [root@centos7 scripts]# pssh -h host.txt -i ls -l /data [1] 12:57:04 [FAILURE] 192.168.209.10 Exited with error code 2 Stderr: ls: cannot access /data: No such file or directory [2] 12:57:05 [SUCCESS] 192.168.209.109 -rw-r--r--. 1 root root 0 May 7 00:56 test.txt 3、-o 标准正确和-e 标准错误重定向 #将标准错误和标准正确重定向分别保存至本地主机的/data/stdout和/data/stderr目录下 [root@centos7 scripts]# pssh -h host.txt -o /data/stdout -e /data/stderr -i hostname [1] 12:59:51 [SUCCESS] 192.168.209.10 c7-client [2] 12:59:52 [SUCCESS] 192.168.209.109 centos8.1 #分别在stdout和stderr下建立以主机ip命名的文件 [root@centos7 scripts]# ls /data/stdout/ 192.168.209.10 192.168.209.109 [root@centos7 scripts]# cat /data/stdout/192.168.209.10 c7-client [root@centos7 scripts]# cat /data/stdout/192.168.209.109 centos8.1 #存放错误信息 [root@centos7 scripts]# pssh -h host.txt -o /data/stdout -e /data/stderr -i hsotname [1] 13:20:39 [FAILURE] 192.168.209.10 Exited with error code 127 Stderr: bash: hsotname: command not found [2] 13:20:39 [FAILURE] 192.168.209.109 Exited with error code 127 Stderr: bash: hsotname: command not found [root@centos7 scripts]# cat /data/stderr/192.168.209.10 bash: hsotname: command not found [root@centos7 scripts]# cat /data/stderr/192.168.209.109 bash: hsotname: command not found #再次执行命令,会覆盖原来的文件内容 [root@centos7 scripts]# pssh -h host.txt -o /data/stdout -e /data/stderr -i cat /etc/redhat-release [1] 13:21:41 [SUCCESS] 192.168.209.10 CentOS Linux release 7.6.1810 (Core) [2] 13:21:42 [SUCCESS] 192.168.209.109 CentOS Linux release 8.1.1911 (Core) [root@centos7 scripts]# cat /data/stderr/192.168.209.10 #无消息 [root@centos7 scripts]# cat /data/stderr/192.168.209.109 [root@centos7 scripts]# cat /data/stdout/192.168.209.109 #存放刚执行命令的内容 CentOS Linux release 8.1.1911 (Core) 4、内置变量 #变量需要加单引号引起来,否则显示的是当前主机的信息 [root@centos7 scripts]# pssh -h host.txt -i echo $UID [1] 13:25:09 [SUCCESS] 192.168.209.10 0 #其实是centos7的uid [2] 13:25:09 [SUCCESS] 192.168.209.109 0 #同上 #切换一下用户,显示UID [wang@centos7 scripts]$ pssh -H 192.168.209.109 -A -i echo $UID Warning: do not enter your password if anyone else has superuser privileges or access to your account. Password: [1] 13:34:11 [SUCCESS] 192.168.209.109 2007 #变量不加'',显示的是当前主机centos7的wang用户UID [wang@centos7 scripts]$ pssh -H 192.168.209.109 -A -i echo '$UID' Warning: do not enter your password if anyone else has superuser privileges or access to your account. Password: [1] 13:34:24 [SUCCESS] 192.168.209.109 1000 #加上'',显示的就是109主机的wang用户UID #直接使用内置变量,显示的是当前主机的信息 [root@centos7 scripts]# pssh -h host.txt -i echo $HOSTNAME [1] 13:25:18 [SUCCESS] 192.168.209.10 centos7 [2] 13:25:19 [SUCCESS] 192.168.209.109 centos7 #使用''引起来,才能正确识别变量 [root@centos7 scripts]# pssh -h host.txt -i echo '$HOSTNAME' [1] 13:25:30 [SUCCESS] 192.168.209.10 c7-client [2] 13:25:30 [SUCCESS] 192.168.209.109 centos8.1 [root@centos7 scripts]# pssh -h host.txt -i echo "$HOSTNAME" [1] 13:25:37 [SUCCESS] 192.168.209.10 centos7 [2] 13:25:37 [SUCCESS] 192.168.209.109 centos7 5、*需要用双或单引号引起来 #不使用引号 [root@centos7 scripts]# pssh -h host.txt -i ls /data/* [1] 13:42:25 [FAILURE] 192.168.209.10 Exited with error code 2 [2] 13:42:25 [FAILURE] 192.168.209.109 Exited with error code 2 #使用单双引号都可以 [root@centos7 scripts]# pssh -h host.txt -i "ls /data/*" [1] 13:42:39 [FAILURE] 192.168.209.10 Exited with error code 2 Stderr: ls: cannot access /data/*: No such file or directory #10服务器上没有/data目录 [2] 13:42:39 [SUCCESS] 192.168.209.109 /data/test.txt [root@centos7 scripts]# pssh -h host.txt -i 'ls /data/*' [1] 13:42:49 [FAILURE] 192.168.209.10 Exited with error code 2 Stderr: ls: cannot access /data/*: No such file or directory #同上 [2] 13:42:49 [SUCCESS] 192.168.209.109 /data/test.txt3.1.3.2 pscp.pssh命令
pscp.pssh功能是将本地文件批量复制到远程主机
pscp [-vAr] [-h hosts_file] [-H [user@]host[:port]] [-l user] [-p par] [-o outdir] [-e errdir] [-t timeout] [-O options] [-x args] [-X arg] local remotepscp-pssh选项
-v #显示复制过程 -r #递归复制目录范例:
#初始化文件,基于key验证的前提下 [root@centos7 scripts]# cat test.sh hostname [root@centos7 scripts]# chmod +x test.sh #将本地test.sh 复制到/app/目录,app目录要存在 [root@centos7 scripts]# pscp.pssh -h host.txt /scripts/test.sh /app/ [1] 13:51:35 [FAILURE] 192.168.209.10 Exited with error code 1 [2] 13:51:35 [FAILURE] 192.168.209.109 Exited with error code 1 #/app后未加/,意思是把test.sh复制到/下,改名为app [root@centos7 scripts]# pscp.pssh -h host.txt /scripts/test.sh /app [1] 13:52:34 [SUCCESS] 192.168.209.10 [2] 13:52:35 [SUCCESS] 192.168.209.109 [root@centos7 scripts]# pssh -h host.txt -i "ls /app" [1] 13:52:49 [SUCCESS] 192.168.209.10 /app [2] 13:52:50 [SUCCESS] 192.168.209.109 /app [root@c7-client ~]# /app c7-client #未有key验证,需要加-A选项 [root@centos7 scripts]# pscp.pssh -A -h host.txt /scripts/test.sh /tmp/ Warning: do not enter your password if anyone else has superuser privileges or access to your account. Password: [1] 14:04:10 [SUCCESS] 192.168.209.10 [2] 14:04:10 [SUCCESS] 192.168.209.109 [root@centos7 scripts]# pssh -h host.txt -i "ls -l /tmp/test.sh" [1] 14:04:42 [SUCCESS] 192.168.209.10 -rwxr-xr-x 1 root root 9 May 7 14:07 /tmp/test.sh [2] 14:04:42 [SUCCESS] 192.168.209.109 -rwxr-xr-x. 1 root root 9 May 7 02:04 /tmp/test.sh #将本地多个文件批量复制到/tmp/目录 [root@centos7 scripts]# pscp.pssh -h host.txt /scripts/*.sh /tmp/ [1] 14:05:43 [SUCCESS] 192.168.209.10 [2] 14:05:44 [SUCCESS] 192.168.209.109 [root@centos7 scripts]# pssh -h host.txt -i "ls /tmp/*.sh" [1] 14:08:01 [SUCCESS] 192.168.209.10 /tmp/deny_dos1.sh /tmp/deny_dos.sh /tmp/httpd.sh /tmp/ping.sh /tmp/rich.sh /tmp/sshpass_autokey.sh /tmp/systeminfo.sh /tmp/test.sh /tmp/username.sh [2] 14:08:01 [SUCCESS] 192.168.209.109 /tmp/deny_dos1.sh /tmp/deny_dos.sh /tmp/httpd.sh /tmp/ping.sh /tmp/rich.sh /tmp/sshpass_autokey.sh /tmp/systeminfo.sh /tmp/test.sh /tmp/username.sh [root@centos7 scripts]# pscp.pssh -h host.txt /scripts/httpd.sh /data/f1.txt /tmp/ [1] 14:06:21 [SUCCESS] 192.168.209.10 [2] 14:06:21 [SUCCESS] 192.168.209.109 [root@centos7 scripts]# pssh -h host.txt -i "ls -l /tmp/httpd.sh /tmp/f1.txt" [1] 14:06:51 [SUCCESS] 192.168.209.10 -rw-r--r-- 1 root root 7 May 7 14:09 /tmp/f1.txt -rw-r--r-- 1 root root 2253 May 7 14:09 /tmp/httpd.sh [2] 14:06:51 [SUCCESS] 192.168.209.109 -rw-r--r--. 1 root root 7 May 7 02:06 /tmp/f1.txt -rw-r--r--. 1 root root 2253 May 7 02:06 /tmp/httpd.sh #-r选项,递归复制目录及文件,将本地目录批量复制到/tmp/目录 [root@centos7 scripts]# pscp.pssh -h host.txt -r /scripts/ /tmp/ [1] 14:10:45 [SUCCESS] 192.168.209.10 [2] 14:10:45 [SUCCESS] 192.168.209.109 [root@centos7 scripts]# pssh -h host.txt -i "tree /tmp/scripts" [1] 14:14:05 [SUCCESS] 192.168.209.10 /tmp/scripts ├── deny_dos1.sh ├── deny_dos.sh ├── hosts.log ├── host.txt ├── httpd.sh ├── ping.sh ├── rich.sh ├── sshpass_autokey.sh ├── systeminfo.sh ├── test │ └── test.txt ├── test.sh ├── test.sh.bk ├── test.txt └── username.sh 1 directory, 14 files [2] 14:14:05 [SUCCESS] 192.168.209.109 #同209.10主机的内容3.1.3.3 pslurp命令
pslurp功能是将远程主机的文件批量复制到本地
pslurp [-vAr] [-h hosts_file] [-H [user@]host[:port]] [-l user] [-p par][-o outdir] [-e errdir] [-t timeout] [-O options] [-x args] [-X arg] [-L localdir] remote local(本地名)pslurp选项
-L #指定从远程主机下载到本机的存储的目录,local是下载到本地后的名称 -r #递归复制目录范例:
#批量下载目标服务器的passwd文件至/app下,并更名为user [root@centos7 scripts]# pslurp -h host.txt -L /data/ /etc/redhat-release version [1] 14:19:52 [SUCCESS] 192.168.209.10 [2] 14:19:52 [SUCCESS] 192.168.209.109 [root@centos7 scripts]# tree /data /data ├── 192.168.209.10 │ └── version ├── 192.168.209.109 │ └── version 2 directories, 2 files [root@centos7 scripts]#