1. 使用jdk自带的runtime类和process类实现
public static void main(string[] args){ process proc = runtime.getruntime().exec("cd /home/tom; ls;") // 标准输入流(必须写在 waitfor 之前) string instr = consumeinputstream(proc.getinputstream()); // 标准错误流(必须写在 waitfor 之前) string errstr = consumeinputstream(proc.geterrorstream()); int retcode = proc.waitfor(); if(retcode == 0){ system.out.println("程序正常执行结束"); } } /** * 消费inputstream,并返回 */ public static string consumeinputstream(inputstream is){ bufferedreader br = new bufferedreader(new inputstreamreader(is)); string s ; stringbuilder sb = new stringbuilder(); while((s=br.readline())!=null){ system.out.println(s); sb.append(s); } return sb.tostring(); }
2. ganymed-ssh2 实现
pom
<!--ganymed-ssh2包--> <dependency> <groupid>ch.ethz.ganymed</groupid> <artifactid>ganymed-ssh2</artifactid> <version>build210</version> </dependency>
import ch.ethz.ssh2.connection; import ch.ethz.ssh2.session; public static void main(string[] args){ string host = "210.38.162.181"; int port = 22; string username = "root"; string password = "root"; // 创建连接 connection conn = new connection(host, port); // 启动连接 conn.connection(); // 验证用户密码 conn.authenticatewithpassword(username, password); session session = conn.opensession(); session.execcommand("cd /home/winnie; ls;"); // 消费所有输入流 string instr = consumeinputstream(session.getstdout()); string errstr = consumeinputstream(session.getstderr()); session.close; conn.close(); } /** * 消费inputstream,并返回 */ public static string consumeinputstream(inputstream is){ bufferedreader br = new bufferedreader(new inputstreamreader(is)); string s ; stringbuilder sb = new stringbuilder(); while((s=br.readline())!=null){ system.out.println(s); sb.append(s); } return sb.tostring(); }
3. jsch实现
pom
<dependency> <groupid>com.jcraft</groupid> <artifactid>jsch</artifactid> <version>0.1.55</version> </dependency>
import com.jcraft.jsch.jsch; import com.jcraft.jsch.session; public static void main(string[] args){ string host = "210.38.162.181"; int port = 22; string username = "root"; string password = "root"; // 创建jsch jsch jsch = new jsch(); // 获取session session session = jsch.getsession(username, host, port); session.setpassword(password); properties prop = new properties(); prop.put("stricthostkeychecking", "no"); session.setproperties(prop); // 启动连接 session.connect(); channelexec exec = (channelexec)session.openchannel("exec"); exec.setcommand("cd /home/winnie; ls;"); exec.setinputstream(null); exec.seterrstream(system.err); exec.connect(); // 消费所有输入流,必须在exec之后 string instr = consumeinputstream(exec.getinputstream()); string errstr = consumeinputstream(exec.geterrstream()); exec.disconnect(); session.disconnect(); } /** * 消费inputstream,并返回 */ public static string consumeinputstream(inputstream is){ bufferedreader br = new bufferedreader(new inputstreamreader(is)); string s ; stringbuilder sb = new stringbuilder(); while((s=br.readline())!=null){ system.out.println(s); sb.append(s); } return sb.tostring(); }
4. 完整代码:
执行shell命令
<dependency> <groupid>commons-io</groupid> <artifactid>commons-io</artifactid> <version>2.6</version> </dependency> <dependency> <groupid>com.jcraft</groupid> <artifactid>jsch</artifactid> <version>0.1.55</version> </dependency> <dependency> <groupid>ch.ethz.ganymed</groupid> <artifactid>ganymed-ssh2</artifactid> <version>build210</version> </dependency>
import cn.hutool.core.io.ioutil; import com.jcraft.jsch.channelshell; import com.jcraft.jsch.jsch; import com.jcraft.jsch.session; import org.slf4j.logger; import org.slf4j.loggerfactory; import java.io.bufferedreader; import java.io.inputstreamreader; import java.io.printwriter; import java.util.vector; /** * shell脚本调用类 * * @author micky */ public class sshutil { private static final logger logger = loggerfactory.getlogger(sshutil.class); private vector<string> stdout; // 会话session session session; //输入ip、端口、用户名和密码,连接远程服务器 public sshutil(final string ipaddress, final string username, final string password, int port) { try { jsch jsch = new jsch(); session = jsch.getsession(username, ipaddress, port); session.setpassword(password); session.setconfig("stricthostkeychecking", "no"); session.connect(100000); } catch (exception e) { e.printstacktrace(); } } public int execute(final string command) { int returncode = 0; channelshell channel = null; printwriter printwriter = null; bufferedreader input = null; stdout = new vector<string>(); try { channel = (channelshell) session.openchannel("shell"); channel.connect(); input = new bufferedreader(new inputstreamreader(channel.getinputstream())); printwriter = new printwriter(channel.getoutputstream()); printwriter.println(command); printwriter.println("exit"); printwriter.flush(); logger.info("the remote command is: "); string line; while ((line = input.readline()) != null) { stdout.add(line); system.out.println(line); } } catch (exception e) { e.printstacktrace(); return -1; }finally { ioutil.close(printwriter); ioutil.close(input); if (channel != null) { channel.disconnect(); } } return returncode; } // 断开连接 public void close(){ if (session != null) { session.disconnect(); } } // 执行命令获取执行结果 public string executeforresult(string command) { execute(command); stringbuilder sb = new stringbuilder(); for (string str : stdout) { sb.append(str); } return sb.tostring(); } public static void main(string[] args) { string cmd = "ls /opt/"; sshutil execute = new sshutil("xxx","abc","xxx",22); // 执行命令 string result = execute.executeforresult(cmd); system.out.println(result); execute.close(); } }
下载和上传文件
/** * 下载和上传文件 */ public class scpclientutil { private string ip; private int port; private string username; private string password; static private scpclientutil instance; static synchronized public scpclientutil getinstance(string ip, int port, string username, string passward) { if (instance == null) { instance = new scpclientutil(ip, port, username, passward); } return instance; } public scpclientutil(string ip, int port, string username, string passward) { this.ip = ip; this.port = port; this.username = username; this.password = passward; } public void getfile(string remotefile, string localtargetdirectory) { connection conn = new connection(ip, port); try { conn.connect(); boolean isauthenticated = conn.authenticatewithpassword(username, password); if (!isauthenticated) { system.err.println("authentication failed"); } scpclient client = new scpclient(conn); client.get(remotefile, localtargetdirectory); } catch (ioexception ex) { ex.printstacktrace(); }finally{ conn.close(); } } public void putfile(string localfile, string remotetargetdirectory) { putfile(localfile, null, remotetargetdirectory); } public void putfile(string localfile, string remotefilename, string remotetargetdirectory) { putfile(localfile, remotefilename, remotetargetdirectory,null); } public void putfile(string localfile, string remotefilename, string remotetargetdirectory, string mode) { connection conn = new connection(ip, port); try { conn.connect(); boolean isauthenticated = conn.authenticatewithpassword(username, password); if (!isauthenticated) { system.err.println("authentication failed"); } scpclient client = new scpclient(conn); if ((mode == null) || (mode.length() == 0)) { mode = "0600"; } if (remotefilename == null) { client.put(localfile, remotetargetdirectory); } else { client.put(localfile, remotefilename, remotetargetdirectory, mode); } } catch (ioexception ex) { ex.printstacktrace(); }finally{ conn.close(); } } public static void main(string[] args) { scpclientutil scpclient = scpclientutil.getinstance("xxx", 22, "xxx", "xxx"); // 从远程服务器/opt下的index.html下载到本地项目根路径下 scpclient.getfile("/opt/index.html","./"); // 把本地项目下根路径下的index.html上传到远程服务器/opt目录下 scpclient.putfile("./index.html","/opt"); } }
总结
到此这篇关于java远程连接linux执行命令的3种方式的文章就介绍到这了,更多相关java远程连接linux执行命令内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论