Batch Modify remote CentOS server passwords

Source: Internet
Author: User
Tags centos server ssh port

The company now has more than 100 servers. You need to modify the root password in batches for the servers, and create a user for each server. If you modify the root password for each server, it is estimated that I will not be able to do it again in the afternoon. The first thing I think of is my favorite php, which has an ssh2 module. I have to admit that using php to handle such a task is very tangled, then I thought about using shell, but I found that I couldn't write it anymore soon. The interaction ability of shell is still not flattering. Finally, I found CT and CT with its powerful interaction ability, it is undoubtedly the first choice for processing such tasks. In addition, javasct can be embedded with shell, which makes it more powerful.

Method 1PassSecondary CTBatch ModificationLinuxServer username and password

First, you must have a list of server ip addresses. Put the ip addresses to be processed in the list.

192.168.6.236

192.168.6.235

192.168.6.234

192.168.6.233

192.168.6.6.2

192.168.6.231

.....

Then there is the shell script shell. sh.

#! /Bin/bash

If ["$1" = ""] | ["$2" = ""] | ["$1" = "-- help"] ["$1" = "-h"]

Then

Echo "usage: shell. sh path/iplist path/adduser"

Exit

Fi

Cat $1 | while readline

Do

[-Z $ line] & continue

$2 $ line;

Done

Echo-e "\ n well done \ n"

The following is the most important part of adduser

#! /Usr/bin/CT

# Login Username

Set loginuser ""

# Password

Set loginpass ""

# Username to be modified

Set passuser "dfdjfk"

# New password to be modified

Set newpass "your new password"

# New User name to be added

Set newusername "newusername"

# Password of the new user to be added

Set newpasswd "newpasswd"

Set ipaddr [lrange $ argv 0 0]

Set timeout 300

Set performance_prompt "] # | ~]? "

# --------------------------------------------------- Log on through ssh

Spawn ssh $ loginuser @ $ ipaddr

Set timeout 300

CT {

-Re "Are you sure you want tocontinue connecting (yes/no )? "{

Send "yes \ r"

}-Re "assword :"{

Send "$ loginpass \ r"

}-Re "Permission denied, please tryagain ."{

Exit

}-Re "Connection refused "{

Exit

} Timeout {

Exit

} Eof {

Exit

}

}

CT {

-Re "assword :"{

Send "$ loginpass \ r"

}

-Re $ pai_prompt {

Send "\ r"

}

}

# ------------------------------------------- Change the password

Send "passwd $ passuser \ r ";

CT {

"New UNIX password :"{

Send "$ newpass \ r"

}

"Passwd: Only root can specify a username ."{

Exit

}

}

CT {

"Retype new UNIX password :"{

Send "$ newpass \ r"

}

}

# ------------------------------------------------------ Add a new user and change the password

CT-re $ pai_prompt

Sleep 1

Send "useradd $ newusername \ r"

Sleep 1

Send "passwd $ newusername \ r ";

CT {

"New UNIX password :"{

Send "$ newpasswd \ r"

}

"Passwd: Only root can specify a username ."{

Exit

}

}

CT {

"Retype new UNIX password :"{

Send "$ newpasswd \ r"

}

}

# --------------------------------------------- Exit

CT-re $ pai_prompt

Exit

It took nearly one afternoon to complete debugging.

Method 2PassShellScript to change passwords in batches

#! /Bin/bash
# BY kerryhu
# MAIL: king_819@163.com
# BLOG: http://kerry.blog.51cto.com
# Please manual operation yum of before Operation .....

1. Establish trust relationships

192.168.9.203 is the Administrator

192.168.9.201 192.168.9.202 is a remote linux Server

1. Generate certificates and,

[Root @ manage ~] # Ssh-keygen-t rsa(Then press enter all the way)

Generating public/private rsa key pair.

Enter file in which to save the key (/root/. ssh/id_rsa ):

Enter passphrase (empty for no passphrase ):

Enter same passphrase again:

Your identification has been saved in/root/. ssh/id_rsa. (private key)

Your public key has been saved in/root/. ssh/id_rsa.pub. (public key)

The key fingerprint is:

36: ec: fc: db: b0: 7f: 81: 7e: d0: 1d: 36: 5e: 29: dd: 5b: a0

2. Send the public key on the management machine to each remote server.

If the remote server changes the default ssh port number, use scp-P 17173,17173 as the port number.

[Root @ manage. ssh] # scp id_rsa.pub192.168.9.201:/root/. ssh/authorized_keys

[Root @ manage. ssh] # scp id_rsa.pub192.168.9.202:/root/. ssh/authorized_keys

The management machine and remote host trust relationship have been established

Note:No trust relationship is established. Further steps are required.

InGNOMESettingsSsh-agent
If you are in the GNOME runtime environment, perform the following steps to configure the ssh-agent.ssh-agent tool the user saves your DSA key passphrase so that each time you ssh or scp to Machine B. when you log on to GNOME, openssh-askpass-gnome prompts you to enter passphrase and save it until you exit GNOME. in this GNOMEsession, when ssh or scp is connected to Machine B, the system no longer requires you to enter passphrase.
To save passphrase In the GNOME session, follow these steps:
1. select Main Menu Button (on the Panel) => Preferences => MorePreferences => Sessions, and click the Startup Programs tab. click Add and enter/usr/bin/ssh-add in the StartupCommand text box. set a priority number lower than any existing command to ensure that it is finally executed. A good ssh-add priority number is 70 or above. the higher the priority, the lower the priority. if there are other programs, this program (ssh-add) should be the lowest priority. click Close to exit.
2. log on to GNOME again, that is, restart X. after GNOME is started, a dialog box appears asking you to enter passphrase (s ). if you have configured the DSA and RSA key pairs, you are prompted to enter them. in the future, ssh, scp, or sftp will no longer require you to enter the password.

NonXEnvironment ConfigurationSsh-agent
If X is not running, configure ssh-agent as follows. if GNOME is running but you do not want to prompt passphrase when you log in, the following procedure will be performed in the terminal window, such as XTerm. if the X you run is not GNOME, the following operations will be performed in the terminal window. however, your passphrase is only remembered by the terminal window, not set globally.

1. Enter the following command at the shell prompt:
Exec/usr/bin/ssh-agent $ SHELL

2. Enter the following command:
Ssh-add
Enter your passphrase (s). If you have configured a multi-pair key, the system will prompt you to enter one by one.

3. After exiting the system, passphrase (s) will be released. These two commands must be executed each time you log on to the virtual console or terminal window.

2. Batch Modify remote server passwords using shell scripts

If you want to call mkpasswd, You have to install keep CT. You can use mkpasswd to generate a random password.

Usage: mkpasswd [args] [user]

Where arguments are:

-L # (length of password, default = 10)

-D # (min # of digits, default = 2)

-C # (min # of lowercase chars, default = 2)

-C # (min # of uppercase chars, default = 2)

-S # (min # of special chars, default = 1)

-V (verbose, show passwd interaction)

-P prog (program to setpassword, default = passwd)

For example, if you want to specify a password with a length of 8 and at least three uppercase letters, you can enter:

Mkpasswd-l 8-C 3. All right, the password will be generated randomly according to your requirements.

Yum-y install benchmark CT

Ip_list.txt is the IP address list of the remote server.

[Root @ manage. ssh] # catip_list.txt

192.168.9.201

192.168.9.202

If the remote server modifies the default ssh port number, use ssh-p 17173,17173 as the port number.

#! /Bin/bash

#================= Though ssh remote server, auto modifyROOT passwd ============== #

For IP in 'cat/root/ip_list.txt '# import the IP address of the host to be modified remotely

Do

#================================== Create a remote host password ============ ======================== #

TMP_PWD = 'mkpasswd-l 8-C 3' the red font can be written as the password you need

R_PWD = 'echo $ {IP }_$ {TMP_PWD} 'the password you need in the red font.

Echo "$ {IP }_$ {TMP_PWD}"> R_PWD.txt can be written in red as the password you need.

#=======================================Change the remote host password ========== ======================== #

If [$? = 0]; then

Ssh $ IP passwd root -- stdin <R_PWD.txt

Echo-e "$ (date" + % Y-% m-% d % H: % M: % S ") \ t $ {IP} \ t $ {R_PWD} \ t "> R_Server.log

Else

Echo-e "$ (date" + % Y-% m-% d % H: % M: % S ") \ t $ {IP} R_PWD.txt is create fail \ tplease check! \ T "> M_pass.log

Fi

If [$? = 0]; then

Echo-e "$ (date" + % Y-% m-% d % H: % M: % S ") \ tThe $ {IP} passwd is modify OK \ t "> M_pass.log

Else

Echo-e "$ (date" + % Y-% m-% d % H: % M: % S ") \ tThe $ {IP} passwd is modify fail \ tpleasecheck! \ T "> M_pass.log

Fi

Done

Another example of the second method

Create SSH Trust

Use host A as the client (initiate an SSH request)

Use host B as the server (receiving ssh requests)

The above lists the hosts that actively initiate SSH login requests and the hosts that receive the requests.

1.

Host A generates A public/private key certificate

[Root @ buddytj-10. ssh] #Ssh-keygen-t rsa # rsa algorithm Certificate

Generating public/private rsa keypair. (Press ENTER below)

Enter file in which to save the key (/root/. ssh/id_rsa ):

/Root/. ssh/id_rsa already exists.

Overwrite (y/n )? Y (because my certificate already exists, overwrite it)

Enter passphrase (empty for nopassphrase ):

Enter same passphrase again:

Your identification has been savedin/root/. ssh/id_rsa. (private key)

Your public key has been saved in/root/. ssh/id_rsa.pub. (public key)

The key fingerprint is:

C1: 26: cc: 88: 2b: 05: dd: c3: 6b: 1e: 78: 5d: da: 9c: da: 8a

Root @ buddytj-10

The certificate is generated. Id_rsa (Private Key) | id_rsa.pub (Public Key)

2.

Pass the Public Key generated by host A to host B

[Root @ buddytj-10. ssh] #Scp id_rsa.pub60.28. *. *:/root/. ssh/

3.

Rename A's public key on host B

[Root @ buddytj-11. ssh] #Mv id_rsa.pubauthorized_keys

4. Now the work of remote SSH from host A to host B is completed.

Ultra EASY

========================================================== ========================================================

II

========================================================== ========================================================

Modify host B's SHELL Password

A #Echo 'your _ config_passwd '> passwd.txt (create a password file and enter the password you want)

#Ssh 60. 28. *. * passwd root -- stdin3.

========================================================== ========================================================

Batch Modify host passwords (continue to complete !!!!!!!!!!!!!!!)

Batch SHELL small examples, some of which are not perfect! Note:

#! /Bin/bash

################## Thoughssh remote server, auto modify ROOT passwd ###########

For IP in 'cat/root/ip_list.txt '##### import the IP address of the remote host to be modified #################

Do

############# Obtain the remote host username ##################### ##########################

############ This program obtains the remote host name and adds its own private password for each device using this name ###

############# If the passwords are consistent, do not follow the same model ###################################### #######

R_HOSTNAME = 'ssh $ IP cat/etc/sysconfig/network | awk-F = '/HOSTNAME/{print $2 }''

# Echo $ R_HOSTNAME

################# Create a remote host password ################### #############################

CREATE_PWD = 'echo $ R_HOSTNAME | awk-F-'{print $2}' | tr' [a-z] ''[A-Z]''

Echo "$ {CREATE_PWD} 123"> passwd. tmp

################### Modify the remote host password ################# #############################

If [$? = 0]; then

Ssh $ IPpasswd root -- stdin

If [$? = 0]; then

Echo "The $ R_HOSTNAME ($ IP) passwd is modify OK"

Else

Echo-e "The $ R_HOSTNAME ($ IP) passwd is modify fail \ n"

Echo "please you check"

Fi

Done

Script successfully tested

1, Establish a trust relationship

Establish SSH mutual trust between the same user on host A, host B, and host C:

1. Generate A key pair on host A user hcwang (e.g.
$ Ssh-keygen-t rsa
2. Go to the. ssh directory.
$ Mv id_rsa.pub authorized_keys // (change to the default public key file name)
3. Transmit the Public Key id_rsa.pub to the target host B, C
$ Scp id_rsa.pub B: $ HOME/. ssh
$ Cat id_rsa.pub> authorized_keys // if no authorized_keys exists, run the mv id_rsa.pubauthorized_keys command.
Similarly, for host C
$ Scp id_rsa.pub C: $ HOME/. ssh
$ Cat id_rsa.pub> authorized_keys

At this point, you can directly SSH from host A to host B and C without A password. If you want to SSH from host B or C, SSH to host A, or between host BC, you need A password. The solution is as follows:

4. Copy the private key and id_rsa of host A to the $ HOME/. ssh directory of host B and C.
$ Scp id_rsa B: $ HOME/. ssh
$ Scp id_rsa C: $ HOME/. ssh

~ OK

2, Create IPList(IP address for which the account password needs to be modifiedAddress)

[Root @ test ~] # Cat ip_list.txt

192.168.10.126

192.168.10.127

192.168.10.128

3, Write SHELLScript

[Root @ test ~] # Cat 1ch. sh

#! /Bin/bash

#================= Though ssh remote server, automodify ROOT passwd ================ #

For IP in 'cat/root/iplist'

Do

#===================================== Mkpasswd ================== ================ #

# TMP_PWD = 'jiguang'

R_PWD = 'echo "jiguang "'

Echo "jiguang"> R_PWD.txt

#================================ CHPASSWD ============ ================ #

If [$? = 0]; then

Ssh $ IPpasswd root -- stdin <R_PWD.txt

Echo-e "$ (date" + % Y-% m-% d % H: % M: % S ") \ t $ {IP} \ t $ {R_PWD} \ t "> R_Server.log

Else

Echo-e "$ (date" + % Y-% m-% d % H: % M: % S ") \ t $ {IP} R_PWD.txt is createfail \ tplease check! \ T "> M_pass.log

Fi

If [$? = 0]; then

Echo-e "$ (date" + % Y-% m-% d % H: % M: % S ") \ tThe $ {IP} passwd is modifyOK \ t "> M_pass.log

Else

Echo-e "$ (date" + % Y-% m-% d % H: % M: % S ") \ tThe $ {IP} passwd is modify fail \ tpleasecheck! \ T "> M_pass.log

Fi

Done

[Root @ test ~] #

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.