Jsch ssh登陆
生活随笔
收集整理的這篇文章主要介紹了
Jsch ssh登陆
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
為什么80%的碼農都做不了架構師?>>> ??
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? Jsch ssh登陸
package com.xxxx;import com.jcraft.jsch.*;import java.io.BufferedReader; import java.io.InputStreamReader;/*** Created by xxx on 2017/4/5.*/ public class JshMain {public static void main(String args[]){JSch jsch = new JSch();try {// Create and connect session.Session session = jsch.getSession("root", "192.168.60.225", 22);session.setPassword("xxxx");session.setUserInfo(new MyUserInfo());session.connect();// Create and connect channel.Channel channel = session.openChannel("exec");((ChannelExec) channel).setCommand("ls");channel.setInputStream(null);BufferedReader input = new BufferedReader(new InputStreamReader(channel.getInputStream()));channel.connect();System.out.println("The remote command is: " + "ls");// Get the output of remote command.String line;while ((line = input.readLine()) != null) {System.out.println(line);}input.close();// Get the return code only after the channel is closed.//if (channel.isClosed()) {// returnCode = channel.getExitStatus();//}// Disconnect the channel and session.channel.disconnect();session.disconnect();} catch (JSchException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (Exception e) {e.printStackTrace();}}}class MyUserInfo implements UserInfo {private String password;private String passphrase;@Overridepublic String getPassphrase() {System.out.println("MyUserInfo.getPassphrase()");return null;}@Overridepublic String getPassword() {System.out.println("MyUserInfo.getPassword()");return null;}@Overridepublic boolean promptPassphrase(final String arg0) {System.out.println("MyUserInfo.promptPassphrase()");System.out.println(arg0);return false;}@Overridepublic boolean promptPassword(final String arg0) {System.out.println("MyUserInfo.promptPassword()");System.out.println(arg0);return false;}//本方法是一個關鍵的問題,返回true就可以@Overridepublic boolean promptYesNo(final String arg0) {System.out.println("MyUserInfo.promptYesNo()");System.out.println(arg0);if (arg0.contains("The authenticity of host")) {return true;}return false;}@Overridepublic void showMessage(final String arg0) {System.out.println("MyUserInfo.showMessage()");} }無密碼登陸
jsch = new JSch();try {session = jsch.getSession("admin", host, 22);String privateKey = "~/.ssh/id_rsa";jsch.addIdentity(privateKey);java.util.Properties config = new java.util.Properties();config.put("StrictHostKeyChecking", "no");session.setConfig(config);session.connect();} catch (Exception e){//log.error("",e);baseResult.setData(e);return baseResult;}?
轉載于:https://my.oschina.net/QAAQ/blog/873459
總結
以上是生活随笔為你收集整理的Jsch ssh登陆的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: PHP结合Ueditor并修改图片上传路
- 下一篇: [LeetCode]Merge Inte