Requirements: WEB apps need to use Jsch to SFTP/SSH access to remote Linux machines via key files
Implementation: Assume that the remote machine has a user named Hadoop user, because the password because the policy requires password changes over time, so you want to use the key to access the machine, so that the password will not be able to access the remote machine.
Rationale: SSH access, the machine being accessed first needs to start the sshd service, and then by default generate RSA public-private key pair by Ssh-keygen.
And you need to configure no password access, that is, you need to put the local public key file into the Authorized_keys file under. SSH, but also to ensure that the file permissions are 600. Note that by default, the passphase required to generate the key remains consistent and can be left blank
, so it's easy to use in code.
In the Jsch code snippet, the connection is established by passing the user name, Ip,passphase, the file that holds the private key.
The same user on the same machine, using the same passphase will also generate different private key files, so you need to save multiple private key files.
The code example at the time of invocation is as follows:
String HostIP = "192.168.1.175"; = Sshexecutil.getinstance (). GetSession2 (HostIP, "Hadoop", "D:/code/learningjava/src/main/resources/hadoop_rsa" ); = (channelexec) sshexecutil.getinstance (). Getchannelexec (session); = "ls-a/"; = sshexecutil.getinstance (). ExecCommand (channelexec, command); SYSTEM.OUT.PRINTLN (result);
The code to generate the session section is as follows:
New Jsch (); Jsch.addidentity (FilePath,""); Session session=jsch.getsession (UserName, HostIP,); UserInfo UI=new customuserinfo (); Session.setuserinfo (UI); New Properties (); Config.put ("stricthostkeychecking", "no"); Session.setconfig (config); Session.connect ();
Need to write a shell script to complete the automatic configuration without password access to local functions, another way to realize is that all machines use the same copy of the public key file. That is, the. SSH content is only generated on one machine, and then packaged and distributed to other machines.
Jsch remote access through a key file