您的位置:首页 > 编程语言 > Java开发

java orion ssh scp 使用案例

2013-03-06 15:20 162 查看
首先得先下载orion-ssh2-214.jar包。

把jar包加入你的classpath然后就可以使用了。

SSH的使用方法如下:

/**
* 执行远程的封存脚本
* @param host
* @param username
* @param password
*/
public static List<String> runRomoteScript(String host, String username, String password, String cmd) throws Exception
{
List<String> result = new ArrayList<String>();
Connection conn = new Connection(host);
conn.connect();
boolean isAuthenticated = conn.authenticateWithPassword(username, password);
if (isAuthenticated == false)
throw new RuntimeException("权限不够");
Session sess = conn.openSession();
sess.execCommand(cmd);
InputStream stdout = new StreamGobbler(sess.getStdout());
BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
while (true)
{
String line = br.readLine();
if (line == null)
break;
System.out.println(line);
result.add(line);
}
sess.close();
conn.close();
return result;
}

从远程获取文件:

/*
* 命令成功执行
*/
public static final String SUCCESS = "SUCCESS";

/**
* 从远程服务器下载文件到本地文件夹
* @param host
* @param username
* @param password
* @param romoteFileName
* @param localDir
*/
public static String getFileFromRemote(String host, String username, String password, String romoteFileName, String localDir)
{
String msg = SSHUtil.SUCCESS;
try
{
Connection conn = new Connection(host);
conn.connect();
boolean isAuthenticated = conn.authenticateWithPassword(username, password);
if (isAuthenticated == false)
return "权限不够!";
File inputFile = new File(localDir);
if(!inputFile.exists())     //如果文件夹不存在,则新建文件夹
{
inputFile.mkdirs();
}
SCPClient scpClient = conn.createSCPClient();
scpClient.get(romoteFileName, localDir);
conn.close();
}
catch (IOException e)
{
return "出现了IO错误!";
}
return msg;
}
以上代码经测试,运行正常,请放心使用。

SCPClient.put
方法可以把文件发送到远程服务器。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: