package com.linkage.interfaces.webservice; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.net.SocketException; import java.util.ArrayList; import java.util.List; import org.apache.commons.net.telnet.TelnetClient; import com.jcraft.jsch.JSchException; import com.linkage.interfaces.webservice.factory.SSHProtocol; /** * Telnet Util * @version 20140410 v.2 */ public class TelnetSample implements Runnable{ private InputStream in; private PrintStream out; private char prompt = '$'; private String server; private String user; private String password; private String command; private String directory; private int port; /** * Overloaded constructor * @param server * @param user * @param password */ public TelnetSample(String server, String user, String password,String directory,String command,Integer port){ this.server = server; this.port = port; this.user = user; this.password = password; this.command = command; this.directory = directory; } /** * Enable thread */ private String curLoginUser = null; /*account Attributes*/ private List<String> iniGrp = new ArrayList<String>(); private SSHProtocol sp; public void run() { login(server,user,password); execCommond(directory,command); } public void login(String server,String username,String password) { sp = new SSHProtocol(server,22); curLoginUser = username; try { sp.connect(username, password); } catch (Exception e) { e.printStackTrace(); } } int status = -1; public boolean execCommond(String directory,String command ){ StringBuffer sb = new StringBuffer(); String cmd="chmod +x "+directory+"/"+command; try { status = sp.execCommand(cmd, sb); if(status==0){ cmd="sh "+directory+"/"+command; status = sp.execCommand(cmd, sb); if(status!=0){ return false; } }else{ return false; } } catch (JSchException e) { e.printStackTrace(); }finally{ this.logout(); } return true; } public void logout(){ if(sp != null) sp.disconnect(); } public boolean isLogin(){ if(sp == null) return false; return sp.isConnected(); } // /** // * test // * @param args // */ public static void main(String[] args) { /*System.out.println(Thread.currentThread().getName() + " 线程运行开始!"); TelnetSample tu1 = new TelnetSample("111.11.1.11", "aaaa", "11111","cd /s1/wxs/sale/businese/program", "./sale_bi.sh /ngbss1/wxwlbss/sale/stock_businese/program/upload/20100521024732.txt 8989 3"); TelnetSample tu2 = new TelnetSample("10.100.10.100", "aaaa", "11111","cd /businese/program", "./sale_bi.sh /ngbss/sale/stock_businese/upload_stock/2010.txt 832 3"); Thread thread1 = new Thread(tu1); thread1.start(); Thread thread2 = new Thread(tu2); thread2.start(); System.out.println(Thread.currentThread().getName() + " 线程运行结束!");*/ TelnetSample tu3 = new TelnetSample("199.199.19.29", "root", "123456","/bss/web/domains/ww_domain", "ShellFtp2014.sh",22); Thread thread1 = new Thread(tu3); thread1.start(); } }
SSHProtocol .java类
package com.linkage.maitain.factory; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PipedInputStream; import java.io.PipedOutputStream; import java.util.Iterator; import java.util.StringTokenizer; import java.util.Vector; import org.apache.log4j.Logger; import com.jcraft.jsch.Channel; import com.jcraft.jsch.ChannelExec; import com.jcraft.jsch.JSch; import com.jcraft.jsch.JSchException; import com.jcraft.jsch.Session; import com.jcraft.jsch.UserInfo; public class SSHProtocol { private static final Logger LOGGER = Logger.getLogger(SSHProtocol.class); public static final UserInfo defaultUserInfo = new UserInfo() { public String getPassphrase() { return null; } public String getPassword() { return null; } public boolean promptPassword(String arg0) { return false; } public boolean promptPassphrase(String arg0) { return false; } public boolean promptYesNo(String arg0) { return true; } public void showMessage(String arg0) { } }; JSch jsch = null; String host; String user; int port = 22; String password; int timeout = 15 * 1000; public static final String RETR_STR = "\n"; private Session session = null; public SSHProtocol(String host, int port, String user, String password) { jsch = new JSch(); this.host = host; this.port = port; this.user = user; this.password = password; } public SSHProtocol(String host, String user, String password) { jsch = new JSch(); this.host = host; this.user = user; this.password = password; } public SSHProtocol(String host, int port) { jsch = new JSch(); this.host = host; this.port = port; } public void setLoginUser(String user, String password) { this.user = user; this.password = password; } public int execCommand(String command, StringBuffer sb) throws JSchException { Channel channel = null; // String result = null; int i; int status = -1; if (command == null || !isConnected()) { return -1; } try { channel = session.openChannel("exec"); // ((ChannelExec) channel).setCommand(command); channel.setInputStream(null); ((ChannelExec) channel).setErrStream(System.err, true); // InputStream in = channel.getInputStream(); channel.connect(); byte[] tmp = new byte[2048]; while (true) { while (in.available() > 0) { i = in.read(tmp, 0, 1024); if (i < 0) { break; } result = new String(tmp, 0, i, "utf-8"); sb.append(result); } if (channel.isClosed()) { status = channel.getExitStatus(); // System.out.println("exit-status: "+status); break; } try { Thread.sleep(200); } catch (Exception ee) { } } channel.disconnect(); } catch (JSchException e) { e.printStackTrace(); throw e; } catch (IOException ex) { ex.printStackTrace(); } return status; } public String execShell(String[] commands, String[] resps, boolean fetch) throws JSchException { Channel channel = null; StringBuffer result = new StringBuffer(); String tmp; int i; boolean execOk = false; if (commands == null || resps == null) { throw new JSchException("Empty commands or responses to ssh."); } else if (commands.length != resps.length) { throw new JSchException( "Commands and responses length not equal to command."); } if (!isConnected()) { throw new JSchException("has not connect to server"); } try { channel = session.openChannel("shell"); PipedInputStream pins = new PipedInputStream(); PipedOutputStream pouts = new PipedOutputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(2048); channel.setInputStream(pins); channel.setOutputStream(out); pouts.connect(pins); channel.connect(); try { Thread.sleep(200); } catch (Exception ex) { ex.printStackTrace(); } for (i = 0; i < commands.length; i++) { if (!commands[i].endsWith(RETR_STR)) { commands[i] += RETR_STR; } pouts.write(commands[i].getBytes()); LOGGER.debug("--------------- commands: "+commands[i]); try { Thread.sleep(2000); } catch (Exception ex) { ex.printStackTrace(); } tmp = out.toString("utf-8"); LOGGER.debug("--------------- resp: "+resps[i]); LOGGER.debug("--------------- return: "+tmp); execOk = isGetSuccessReturn(tmp, resps[i]); if (i == commands.length - 1 && fetch) {// result.append(tmp); } if (execOk && i < commands.length - 1) {// out.reset(); } if (!execOk) { // one command timeout ,then ignore the others throw new JSchException("command " + commands[i] + " execute fails, other commands ignored."); } } channel.disconnect(); return result.toString(); } catch (JSchException e) { e.printStackTrace(); throw e; } catch (Exception e) { e.printStackTrace(); throw new JSchException(e.getMessage()); } } public String execShell(String[] commands, String[] resps, boolean fetch, ShellChannelWrapper shellChannelWrapper) throws JSchException { StringBuffer result = new StringBuffer(); boolean newShellChannel = null == shellChannelWrapper.getShellChannel(); if (null == commands || null == resps) { throw new JSchException("Empty commands or responses to ssh."); } else if (commands.length != resps.length) { throw new JSchException( "Commands and responses length not equal to command."); } if (!isConnected()) { throw new JSchException("has not connect to server"); } try { if (newShellChannel) { shellChannelWrapper.createNewShellChannel(session); } try { Thread.sleep(200); } catch (Exception ex) { ex.printStackTrace(); } shellChannelWrapper.getOut().reset(); for (int i = 0; i < commands.length; i++) { if (!commands[i].endsWith(RETR_STR)) { commands[i] += RETR_STR; } shellChannelWrapper.getPouts().write(commands[i].getBytes()); try { Thread.sleep(2000); } catch (Exception ex) { ex.printStackTrace(); } String tmp = shellChannelWrapper.getOut().toString("utf-8"); boolean execOk = isGetSuccessReturn(tmp, resps[i]); if (i == commands.length - 1 && fetch) {// result.append(tmp); } if (execOk && i < commands.length - 1) {// shellChannelWrapper.getOut().reset(); } if (!execOk) { // one command timeout ,then ignore the others throw new JSchException("command " + commands[i] + " execute fails, other commands ignored."); } } return result.toString(); } catch (JSchException e) { e.printStackTrace(); throw e; } catch (Exception e) { e.printStackTrace(); throw new JSchException(e.getMessage()); } } public String execShellToPrompt(String command, String osprompt, ShellChannelWrapper shellChannelWrapper) throws JSchException { String[] commands = { command }; String[] responses = { osprompt }; String result = execShell(commands, responses, true, shellChannelWrapper); int pos1 = result.lastIndexOf(command); if (pos1 == -1) { pos1 = 0; } else { pos1 = pos1 + command.length(); } result = getActualReqult(result, osprompt, pos1); return result; } public int execCommand(String host, int port, String user, String password, String command, StringBuffer sb) throws JSchException { JSch jsch = new JSch(); String result = null; int i; int status = -1; if (command == null) { return -1; } try { Session session = jsch.getSession(user, host, port); session.setPassword(password); session.setUserInfo(defaultUserInfo); // session.setTimeout(timeout); session.connect(); Channel channel = session.openChannel("exec"); ((ChannelExec) channel).setCommand(command); LOGGER.debug("................"+command); channel.setInputStream(null); ((ChannelExec) channel).setErrStream(System.err, true); InputStream in = channel.getInputStream(); channel.connect(); byte[] tmp = new byte[2048]; while (true) { while (in.available() > 0) { i = in.read(tmp, 0, 1024); if (i < 0) { break; } result = new String(tmp, 0, i, "utf-8"); sb.append(result); } if (channel.isClosed()) { status = channel.getExitStatus(); // System.out.println("exit-status: "+status); break; } try { Thread.sleep(200); } catch (Exception ee) { } } channel.disconnect(); session.disconnect(); } catch (JSchException e) { e.printStackTrace(); throw e; } catch (IOException ex) { ex.printStackTrace(); } return status; } public String parseShellPrompt(String buffer) { String sp = ""; int len = buffer.length(); if (len < 1) { return ""; } int pos_end = len - 1; int pos_begin = 0; char ch = buffer.charAt(pos_end); while (ch == '\r' || ch == '\n') { pos_end--; ch = buffer.charAt(pos_end); } pos_begin = pos_end; ch = buffer.charAt(pos_begin); while (ch != '\r' && ch != '\n') { pos_begin--; ch = buffer.charAt(pos_begin); } sp = buffer.substring(pos_begin + 1, pos_end); return sp; } public void connect(String user, String password) throws JSchException { try { session = jsch.getSession(user, host, port); session.setPassword(password); session.setUserInfo(defaultUserInfo); session.connect(timeout); try { Thread.sleep(200); } catch (Exception ex) { ex.printStackTrace(); } } catch (JSchException e) { e.printStackTrace(); throw e; } } public void connect() throws JSchException { try { session = jsch.getSession(user, host, port); session.setPassword(password); session.setUserInfo(defaultUserInfo); session.connect(); try { Thread.sleep(200); } catch (Exception ex) { ex.printStackTrace(); } } catch (JSchException e) { e.printStackTrace(); throw e; } } public void disconnect() { if (session != null) { session.disconnect(); } } public boolean isConnected() { if (session != null && session.isConnected()) { return true; } else { return false; } } private boolean isGetSuccessReturn(String actualReturn, String wantReturn) throws RuntimeException { Vector<String> wantsuccess = new Vector<String>(); Vector<String> wantfailuer = new Vector<String>(); int i = 0; String strtemp = ""; int itemp = -1; parseWantReturn(wantReturn, wantsuccess, wantfailuer); Iterator<String> iter = wantfailuer.iterator(); while (iter.hasNext()) { strtemp = (String) iter.next(); itemp = actualReturn.indexOf(strtemp); if (-1 != itemp) { throw new RuntimeException(strtemp); } } iter = wantsuccess.iterator(); while (iter.hasNext()) { strtemp = (String) iter.next(); itemp = actualReturn.indexOf(strtemp); if (-1 != itemp) { return true; } } return false; } private void parseWantReturn(String wantReturn, Vector<String> wantSuccess, Vector<String> wantFailure) { String allsuccess = ""; String allfailure = ""; String[] strtemp; int i = 0; if (null == wantReturn) { return; } // parse by "^^" StringTokenizer st = null; /*st = new StringTokenizer(wantReturn, OSPromptType.ERRPROMPTTOKEN); int len = st.countTokens(); if (len != 2) { allfailure = ""; allsuccess = wantReturn; } else { allsuccess = st.nextToken(); allfailure = st.nextToken(); } // parse by ",," if (allsuccess.length() > 0) { st = new StringTokenizer(allsuccess, OSPromptType.PROMPTTOKEN); while (st.hasMoreTokens()) { wantSuccess.add(st.nextToken()); } } if (allfailure.length() > 0) { st = new StringTokenizer(allfailure, OSPromptType.PROMPTTOKEN); while (st.hasMoreTokens()) { wantFailure.add(st.nextToken()); } }*/ } public String getActualReqult(String message, String token, int posBegin) { String actualresult = ""; int pos = 0; pos = message.indexOf(token, posBegin); if (pos == -1) { pos = message.length(); } actualresult = message.substring(posBegin, pos); return actualresult; } public static class ShellChannelWrapper { private Channel shellChannel; private PipedInputStream pins; private PipedOutputStream pouts; private ByteArrayOutputStream out; public void createNewShellChannel(Session jschSession) throws Exception { shellChannel = jschSession.openChannel("shell"); pins = new PipedInputStream(); pouts = new PipedOutputStream(); out = new ByteArrayOutputStream(2048); shellChannel.setInputStream(pins); shellChannel.setOutputStream(out); pouts.connect(pins); shellChannel.connect(); } public Channel getShellChannel() { return shellChannel; } public void setShellChannel(Channel shellChannel) { this.shellChannel = shellChannel; } public PipedInputStream getPins() { return pins; } public void setPins(PipedInputStream pins) { this.pins = pins; } public PipedOutputStream getPouts() { return pouts; } public void setPouts(PipedOutputStream pouts) { this.pouts = pouts; } public ByteArrayOutputStream getOut() { return out; } public void setOut(ByteArrayOutputStream out) { this.out = out; } } /* * public static void main(String[] args) throws Exception { SSHProtocol ssh = * new SSHProtocol("111.111.11.11",22); StringBuffer sb = new * StringBuffer(); int status = -1; String[] commands = {"passwd * test080514","test","test"}; String[] response = {"New password,,New UNIX * password^^Unknown user name", "Retype new password,,Retype new UNIX * password","#"}; String[] commands2 = {"pwd"}; String[] response2 = {"#"}; * String tmp; * * try { ssh.connect("root","123456"); } catch (Exception e) {} * * /*status = ssh.execCommand("useradd test080514", sb); * System.out.println("useradd status = "+status+" result = "+sb); * sb.setLength(0); status = ssh.execCommand("useradd test080514", sb); * System.out.println("useradd(existent user) status = "+status+" result = * "+sb); * * sb.setLength(0); status = ssh.execCommand("usermod -g root test080514", * sb); System.out.println("usermod status = "+status+" result = "+sb); * sb.setLength(0); status = ssh.execCommand("usermod -g root test0805140", * sb); System.out.println("usermod(noexistent user) status = "+status+" * result = "+sb); sb.setLength(0); status = ssh.execCommand("usermod -g * root0 test080514", sb); System.out.println("usermod(existent group) * status = "+status+" result = "+sb); */ // System.out.println("passwd result = "+ssh.execShell(commands, response, // true)); // commands[0] = "passwd test0805140"; // System.out.println("passwd(noexistent user) result = // "+ssh.execShell(commands, response, true)); /* * sb.setLength(0); status = ssh.execCommand("cut -d: -s -f1,2 * /etc/shadow|grep -w test080514", sb); System.out.println("grep status = * "+status+" result = "+sb); sb.setLength(0); status = ssh.execCommand("cut * -d: -s -f1,2 /etc/shadow|grep -w test0805140", sb); * System.out.println("grep(noexistent user) status = "+status+" result = * "+sb); * * * sb.setLength(0); status = ssh.execCommand("userdel test080514", sb); * System.out.println("userdel status = "+status+" result = "+sb); * sb.setLength(0); status = ssh.execCommand("userdel test0805140", sb); * System.out.println("userdel(noexistent user) status = "+status+" result = * "+sb); * * sb.setLength(0); status = ssh.execCommand("cat /etc/passwd", sb); * System.out.println("cat /etc/passwd status = "+status+" result = "+sb); * * sb.setLength(0); status = ssh.execCommand("cat /etc/group", sb); * System.out.println("cat /etc/group status = "+status+" result = "+sb); */ /* * tmp = ssh.execShell(commands2, response2, true); * System.out.println("fetch=true, * pwd=\n"+tmp+"\nshellprompt="+ssh.parseShellPrompt(tmp)); tmp = * ssh.execShell(commands2, response2, false); * System.out.println("fetch=false, * pwd=\n"+tmp+"\nshellprompt="+ssh.parseShellPrompt(tmp)); * * sb.setLength(0); status = ssh.execCommand("su - jiangh", sb); * System.out.println("su status = "+status+" result = "+sb); * sb.setLength(0); status = ssh.execCommand("su - jiangh0", sb); * System.out.println("su(noexistent user) status = "+status+" result = * "+sb); * * sb.setLength(0); status = * ssh.execCommand("111.111.11.11",22,"root","123456","ls -l",sb); * System.out.println("ls status = "+status+" result = "+sb); * sb.setLength(0); status = * ssh.execCommand("111.111.11.11",22,"root","123456","ls0 -l",sb); * System.out.println("ls(error) status = "+status+" result = "+sb); } */ }
相关推荐
在这个场景中,shell脚本被用来组织和执行一系列步骤,包括登录远程服务器、传输文件、监控Tomcat服务的状态以及控制其启动和停止。 接下来是expect工具。Expect是一个用于自动化交互式进程的Tcl扩展,它可以模拟...
要编写一个能获取远程服务器CPU、内存和硬盘使用率的Shell脚本,你需要确保系统已经安装了SNMP工具以及`bc`命令。`bc`是一个交互式的或批处理的算术语言,用于进行浮点数计算,这对于处理可能包含小数的资源利用率...
本文将介绍如何使用Shell脚本将Gitlab备份文件自动定时复制到远程服务器上,并对远程服务器上的Gitlab备份文件进行定时清理。 知识点一:SSH密钥配对 在远程备份过程中,需要实现不需要密码的SSH登录,以便使用...
3. **Shell脚本执行**:在SSH连接建立后,Java程序可以通过执行`exec`命令来运行远程服务器上的Shell脚本。脚本可以包含任意的Linux或Unix命令,甚至复杂的流程控制语句。 4. **输入/输出流处理**:为了获取Shell...
本文将深入探讨如何使用Shell脚本实现服务器进程监控,这不仅有助于及时发现异常情况,还能提高系统的可用性和稳定性。接下来,我们将根据提供的文件信息详细解释其原理、步骤以及实际应用。 #### 一、写作背景 在...
- `remote_dir`:远程服务器的目录路径。 - `local_md5_file`:存储本地文件MD5值的文件名。 - `remote_md5_file`:存储远程文件MD5值的文件名。 2. **获取MD5值**: - 使用`find`命令查找本地指定目录下的所有...
我们使用 SSH 来连接远程 Linux 服务器,并执行相关的命令。 3. Linux 服务器密码的修改:我们使用 Expect 脚本来修改 Linux 服务器的密码。该脚本可以自动地输入密码,并执行相关的命令。 4. 用户和组的管理:在 ...
在IT行业中,有时我们需要远程管理服务器或执行一些系统级的任务,而Boyurl就是这样一个工具,它允许我们通过PHP来远程执行shell脚本,极大地提高了运维效率。这个小巧的工具包含两个主要文件,一个PHP文件(boyurl....
1. ssh 远程到主机;...很多时候我们可能需要远程执行服务器上的脚本来修改账号密码,此时就没有办法进行交互了。 此时可以使用如下两种方式修改密码: 方式1: echo password | passwd testuser --stdin > /dev
接下来,我们将进一步扩展功能,通过Shell脚本实现本地服务器上的文件备份至远程服务器的功能。 **步骤**: 1. **新建脚本文件**: - 创建一个新的脚本文件`backup.sh`。 - 写入以下脚本内容: ```bash #!/bin/...
例如,如果要在远程服务器上执行需要交互式输入的命令`sudo apt-get update`,可以使用以下命令: ```bash ssh -t -p 22 root@192.168.1.100 'sudo apt-get update' ``` ### 二、Shell脚本实例 接下来,我们来看...
总结来说,这个Java程序利用JSch库实现了通过SSH协议在远程服务器上执行Shell脚本的功能,对于自动化运维、远程控制等场景具有重要的应用价值。理解并掌握这部分知识有助于提升Java开发者在系统集成和管理中的能力。
上传文件到远程服务器,下载远程服务器资源。 ShellExecutor exe = new ShellExecutor("192.168.1.1", 22, "USERNAME", "PASSWORD"); if (exe.login()) { ResultEntity resultEntity = exe.execute("ls -ls");...
linux下远程执行命令脚本,可传密码,提升权限
一个通过PHP来远程执行shell脚本工具。整个程序只有两个文件,一个PHP文件,一个shell安装脚本,易于使用和安装。支持PHP5.2+以上的版本。提供的功能包括: 1:用户登录注销。 2:记录每次使用的IP,方便审计。 3...
在Unix/Linux环境中,Shell脚本允许我们编写一系列命令来执行自动化任务。这个脚本的目的就是读取`prov.csv`中的数据,并将其插入到MySQL数据库中的相应表中。脚本可能包含如下步骤: 1. 使用`cat`或`head`命令查看...
在IT行业中,Java语言因其跨平台的特性及丰富的库支持,常常被用来进行远程服务器管理。本主题聚焦于使用Java来操作Linux服务器,特别是通过执行shell脚本来获取服务器的反馈数据。以下将详细阐述这个过程涉及的技术...
常用shell脚本, Dos攻击防范(自动屏蔽攻击IP).sh 一键部署等等 Linux系统发送告警脚本.sh MySQL数据库备份单循环.sh MySQL数据库备份多循环.sh nginx 访问访问日志按天切割.sh nginx.conf nginx访问日志分析...
本文将详细介绍如何利用Shell脚本在Linux系统上实现MySQL数据库的定时自动备份,并通过FTP协议上传至远程服务器。 #### 目标需求分析 目标是开发一个脚本,该脚本能定期执行MySQL数据库的备份,并将这些备份文件...
Shell脚本是用Shell语言编写的程序,允许用户通过命令行界面自动化执行一系列操作。在这个名为"我的几个常用shell脚本"的压缩包中,包含了作者常用的Shell脚本集合,这些脚本可能涵盖日常系统管理、文件处理、数据...