package com.artfess.security.util; /** * @author wh * @Package com.example.demo.win * @date 2020/6/15 13:47 * @Description: */ import com.jcraft.jsch.ChannelExec; import com.jcraft.jsch.JSch; import com.jcraft.jsch.JSchException; import com.jcraft.jsch.Session; import org.apache.commons.io.IOUtils; import java.io.IOException; import java.io.InputStream; public class SSHLinux { public static void main(String[] args) throws IOException, JSchException { String host = "121.36.82.203"; int port = 22; String user = "root"; String password = "artfess@023)@#"; //备份 //String command="mysqldump -uroot -p'artfess@023,.;' test > /opt/test20210419.sql"; //还原 String command="mysql -uroot -p'artfess@023,.;' test < /opt/test20210419.sql"; //String command = "sh /opt/mysqlbackup.sh";//执行sh脚本 //String command = "cd /opt;ls";//多条语句动";"分割 String res = exeCommand(host,port,user,password,command); System.out.println(res); } public static String testConnect(String host, int port, String user, String password) { return exeCommand(host,port,user,password,"lsb_release -a"); } public static String exeCommand(String host, int port, String user, String password, String command) { try { JSch jsch = new JSch(); Session session = jsch.getSession(user, host, port); session.setConfig("StrictHostKeyChecking", "no"); // java.util.Properties config = new java.util.Properties(); // config.put("StrictHostKeyChecking", "no"); session.setPassword(password); session.connect(); ChannelExec channelExec = (ChannelExec) session.openChannel("exec"); InputStream in = channelExec.getInputStream(); channelExec.setCommand(command); channelExec.setErrStream(System.err); channelExec.connect(); String out = IOUtils.toString(in, "UTF-8"); //System.out.println(out); channelExec.disconnect(); session.disconnect(); return out; }catch (Exception e){ return e.getMessage(); } } }