下面列出了java.security.acl.NotOwnerException#com.jcraft.jsch.JSchException 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@ResponseBody
@RequestMapping("/getDilatation")
public List<Line> getDilatation(String ip) throws IOException, MyException,JSchException {
List<Line> lineList=new ArrayList<Line>();
Line lines =new Line(ip);
Forecast forecast=getForecastObject(ip);
if(forecast.getIpAddr()!=null){
long average= forecast.getAverage();
Calendar timeForForecast = Calendar.getInstance();
timeForForecast.setTime(forecast.getTimeForForecast());
lines.getData().add(new Long[] {timeForForecast.getTimeInMillis(),forecast.getWarning()/1024});
for(int i=0;i<12;i++){
long freeMB=(forecast.getWarning()+average*(i+1)*24*30)/1024;
timeForForecast.add(Calendar.MONTH, 1); // 加一个月
// timeForForecast.set(Calendar.DATE, 1); // 设置当前月第一天
lines.getData().add(new Long[] {timeForForecast.getTimeInMillis(), freeMB });
}
}
lineList.add(lines);
return lineList;
}
@RequestMapping("/serverInfo")
public ModelAndView serverInfo(String ip) throws IOException, MyException,JSchException {
ModelAndView mv = new ModelAndView("structure/serverInfo.jsp");
if(ip.indexOf(":")>=0){
String[] data=ip.split(":");
ip=data[0];
}
List<Group> groups=monitorService.listGroupInfo();
for(Group group:groups){
for(Storage storage:group.getStorageList()){
if(storage.getIpAddr().equals(ip)){
mv.addObject("serverInfo", storage);
}
}
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
Calendar calendar = Calendar.getInstance();
mv.addObject("end", sdf.format(calendar.getTime()));
calendar.add(Calendar.HOUR, -1);
mv.addObject("start", sdf.format(calendar.getTime()));
return mv;
}
private JSch createJSchInstance(ServerConfiguration server) throws AgentProxyException, JSchException
{
JSch jSch = new JSch();
if (server.isAgentForwarding())
{
Connector connector = ConnectorFactory.getDefault().createConnector();
jSch.setIdentityRepository(new RemoteIdentityRepository(connector));
}
else if (server.getPrivateKey() != null && server.getPublicKey() != null)
{
String passphrase = server.getPassphrase();
jSch.addIdentity("default", getBytes(server.getPrivateKey()), getBytes(server.getPublicKey()),
passphrase != null ? getBytes(passphrase) : null);
}
return jSch;
}
@Override
protected SshOutput executeCommand(ServerConfiguration serverConfig, Commands commands, ChannelExec channel)
throws JSchException, IOException
{
channel.setAgentForwarding(serverConfig.isAgentForwarding());
SshOutput executionOutput = new SshOutput();
try (ByteArrayOutputStream errorStream = new ByteArrayOutputStream())
{
channel.setCommand(commands.getJoinedCommands());
channel.setErrStream(errorStream);
channel.connect();
executionOutput.setOutputStream(readChannelInputStream(channel));
executionOutput.setErrorStream(new String(errorStream.toByteArray(), StandardCharsets.UTF_8));
executionOutput.setExitStatus(channel.getExitStatus());
}
return executionOutput;
}
/**
* Execute an ssh command on the server, without closing the session
* so that a Reader can be returned with streaming data from the server.
*
* @param command the command to execute.
* @return a Reader with streaming data from the server.
* @throws IOException if it is so.
* @throws SshException if there are any ssh problems.
*/
@Override
public synchronized Reader executeCommandReader(String command) throws SshException, IOException {
if (!isConnected()) {
throw new IllegalStateException("Not connected!");
}
try {
Channel channel = connectSession.openChannel("exec");
((ChannelExec)channel).setCommand(command);
InputStreamReader reader = new InputStreamReader(channel.getInputStream(), "utf-8");
channel.connect();
return reader;
} catch (JSchException ex) {
throw new SshException(ex);
}
}
/**
* Creates SSHShell.
*
* @param host the host name
* @param port the ssh port
* @param userName the ssh user name
* @param password the ssh password
* @return the shell
* @throws JSchException
* @throws IOException
*/
private SshShell(String host, int port, String userName, String password)
throws JSchException, IOException {
Closure expectClosure = getExpectClosure();
for (String linuxPromptPattern : new String[]{"\\>","#", "~#", "~\\$"}) {
try {
Match match = new RegExpMatch(linuxPromptPattern, expectClosure);
linuxPromptMatches.add(match);
} catch (MalformedPatternException malformedEx) {
throw new RuntimeException(malformedEx);
}
}
JSch jsch = new JSch();
this.session = jsch.getSession(userName, host, port);
session.setPassword(password);
Hashtable<String,String> config = new Hashtable<>();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect(60000);
this.channel = (ChannelShell) session.openChannel("shell");
this.expect = new Expect4j(channel.getInputStream(), channel.getOutputStream());
channel.connect();
}
@Test
public void testTestCommand() throws JSchException, IOException {
JSch jsch = new JSch();
Session session = jsch.getSession("admin", "localhost", properties.getShell().getPort());
jsch.addIdentity("src/test/resources/id_rsa");
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
ChannelShell channel = (ChannelShell) session.openChannel("shell");
try (PipedInputStream pis = new PipedInputStream(); PipedOutputStream pos = new PipedOutputStream()) {
channel.setInputStream(new PipedInputStream(pos));
channel.setOutputStream(new PipedOutputStream(pis));
channel.connect();
pos.write("test run bob\r".getBytes(StandardCharsets.UTF_8));
pos.flush();
verifyResponseContains(pis, "test run bob");
}
channel.disconnect();
session.disconnect();
}
/**
* 本地檔案放到遠端SFTP上
*
* @param user
* @param password
* @param addr
* @param port
* @param localFile
* @param remoteFile
* @throws JSchException
* @throws SftpException
* @throws Exception
*/
public static void put(String user, String password, String addr, int port,
List<String> localFile, List<String> remoteFile) throws JSchException, SftpException, Exception {
Session session = getSession(user, password, addr, port);
Channel channel = session.openChannel("sftp");
channel.connect();
ChannelSftp sftpChannel = (ChannelSftp) channel;
try {
for (int i=0; i<localFile.size(); i++) {
String rf=remoteFile.get(i);
String lf=localFile.get(i);
logger.info("put local file: " + lf + " write to " + addr + " :" + rf );
sftpChannel.put(lf, rf);
logger.info("success write to " + addr + " :" + rf);
}
} catch (Exception e) {
e.printStackTrace();
throw e;
} finally {
sftpChannel.exit();
channel.disconnect();
session.disconnect();
}
}
/**
* TODO: メソッドコメントを記述
*
* @param username
* @param privateKey
* @param passphrase
* @param host
* @param port
* @return
*/
public static Session createSessionByPrivateKey(String username, String privateKey, String passphrase, String host,
int port) {
Charset charset = Charset.forName("UTF-8");
byte[] privateKeyBytes = privateKey.getBytes(charset);
byte[] passphraseBytes = null;
if (passphrase != null) {
passphraseBytes = passphrase.getBytes(charset);
}
try {
JSch jsch = new JSch();
jsch.addIdentity("name", privateKeyBytes, null, passphraseBytes);
Session session = jsch.getSession(username, host, port);
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
return session;
} catch (JSchException e) {
throw new AutoException("ECOMMON-000302", username, host, port);
}
}
private static Session getSession(String host, String username, String password, String privateKeyPath)
throws JSchException {
JSch jsch = new JSch();
Session session = null;
if (StringUtils.isNotBlank(privateKeyPath)) {
jsch.addIdentity(privateKeyPath);
}
session = jsch.getSession(username, host, 22);
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
if (StringUtils.isNotBlank(password)) {
session.setPassword(password);
config.put("PreferredAuthentications", "password");
}
session.setConfig(config);
session.connect();
return session;
}
private static void knownHosts(final JSch sch, FS fs) throws JSchException {
final File home = fs.userHome();
if (home == null)
return;
final File known_hosts = new File(new File(home, ".ssh"), "known_hosts"); //$NON-NLS-1$ //$NON-NLS-2$
try {
final FileInputStream in = new FileInputStream(known_hosts);
try {
sch.setKnownHosts(in);
} finally {
in.close();
}
} catch (FileNotFoundException none) {
// Oh well. They don't have a known hosts in home.
} catch (IOException err) {
// Oh well. They don't have a known hosts in home.
}
}
private void setupSSHConnector(SshXpraConnector connector, Connection c) {
try {
final File knownHosts = getFileStreamPath("known_hosts");
knownHosts.createNewFile();
connector.getJsch().setKnownHosts(knownHosts.getAbsolutePath());
if(c.sshPrivateKeyFile != null) {
connector.getJsch().addIdentity(c.sshPrivateKeyFile);
}
if(c.displayId >= 0) {
connector.setDisplay(c.displayId);
}
} catch (JSchException | IOException e) {
// TODO implement some fix if necessary
e.printStackTrace();
}
}
/**
* For creating a JSCH session.
*
* @param host
* the host
* @return a JSCH session
* @throws JSchException
* the jsch exception
*/
private Session createSession(CommandWritable.Command.SwitchedIdentity switchedIdentity, String host, CommandType commandType) throws JSchException {
JSch jsch = new JSch();
Session session = null;
if(switchedIdentity.getPrivatePath() != null && !switchedIdentity.getPrivatePath().isEmpty()){
jsch.addIdentity(switchedIdentity.getPrivatePath());
}
java.util.Properties conf = new java.util.Properties();
session = jsch.getSession(switchedIdentity.getUser(), host, RemotingConstants.TWENTY_TWO);
if(switchedIdentity.getPasswd()!=null){
try{
session.setPassword(StringUtil.getPlain(switchedIdentity.getPasswd()));
}catch(Exception e){
LOGGER.error("Failed to Decrypt the password", e);
}
}
conf.put(STRICT_HOST_KEY_CHECKING, "no");
session.setConfig(conf);
session.connect();
LOGGER.debug("Session Established, for user ["+switchedIdentity.getUser()+"]"+":["+session.isConnected()+"]");
return session;
}
@Override
public BuildFinishedStatus runProcess() {
JSch.setLogger(new JSchBuildLogger(myLogger));
Session session = null;
try {
session = myProvider.getSession();
return executeCommand(session, myPty, myCommands);
} catch (JSchException e) {
logBuildProblem(myLogger, e.getMessage());
LOG.warnAndDebugDetails("Error executing SSH command", e);
return BuildFinishedStatus.FINISHED_FAILED;
} finally {
if (session != null) {
session.disconnect();
}
}
}
public static Session connect(String host, Integer port, String user, String password) throws JSchException{
Session session = null;
try {
JSch jsch = new JSch();
if(port != null){
session = jsch.getSession(user, host, port.intValue());
}else{
session = jsch.getSession(user, host);
}
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
//time out
session.connect(3000);
} catch (JSchException e) {
e.printStackTrace();
System.out.println("SFTPUitl connection error");
throw e;
}
return session;
}
LazyKnownHosts(JSch jsch, String knownHosts) throws JSchException {
if (knownHosts != null) {
try {
final InputStream in = new ByteArrayInputStream(knownHosts.getBytes("UTF8"));
try {
jsch.setKnownHosts(in);
} finally {
in.close();
}
} catch (IOException e) {
// no known hosts
}
}
this.repo = jsch.getHostKeyRepository();
}
@Override
protected JSch createDefaultJSch(FS fs) throws JSchException {
JSch def = super.createDefaultJSch(fs);
String keyName = ServerConfiguration.getInstance().
getFirstProperty(GitDeploymentSynchronizerConstants.SSH_PRIVATE_KEY_NAME);
String keyPath = ServerConfiguration.getInstance().
getFirstProperty(GitDeploymentSynchronizerConstants.SSH_PRIVATE_KEY_PATH);
if (keyName == null || keyName.isEmpty())
keyName = GitDeploymentSynchronizerConstants.SSH_KEY;
if (keyPath == null || keyPath.isEmpty())
keyPath = System.getProperty("user.home") + "/" + GitDeploymentSynchronizerConstants.SSH_KEY_DIRECTORY;
if (keyPath.endsWith("/"))
def.addIdentity(keyPath + keyName);
else
def.addIdentity(keyPath + "/" + keyName);
return def;
}
@RequestMapping("/performance")
public ModelAndView performance() throws IOException, MyException,JSchException {
ModelAndView mv = new ModelAndView("monitor/performance.jsp");
List<Group> groups = monitorService.listGroupInfo();
mv.addObject("groups", groups);
return mv;
}
private void verifySessionConnection(InOrder ordered, ServerConfiguration server, Session session)
throws JSchException
{
ordered.verify(session).setConfig("StrictHostKeyChecking", "no");
ordered.verify(session).setConfig("PreferredAuthentications", "publickey,password");
ordered.verify(session).setPassword(server.getPassword());
ordered.verify(session).connect(30_000);
}
public SecureShellAuthentication(Bucket bucket, AmazonS3 client) {
factory = new JschConfigSessionFactory() {
@Override
public synchronized RemoteSession getSession(URIish uri, CredentialsProvider credentialsProvider, FS fs, int tms) throws TransportException {
// Do not check for default ssh user config
fs.setUserHome(null);
return super.getSession(uri, credentialsProvider, fs, tms);
}
@Override
protected void configure(OpenSshConfig.Host host, Session session) {
session.setConfig("HashKnownHosts", "no");
if ("localhost".equalsIgnoreCase(host.getHostName())) {
session.setConfig("StrictHostKeyChecking", "no");
}
}
@Override
protected void configureJSch(JSch jsch) {
S3Object file;
file = client.getObject(bucket.getName(), ".ssh/known_hosts");
try (InputStream is = file.getObjectContent()) {
jsch.setKnownHosts(is);
} catch (IOException | JSchException e) {
throw new IllegalArgumentException("Missing known hosts file on s3: .ssh/known_hosts", e);
}
file = client.getObject(bucket.getName(), ".ssh/id_rsa");
try (InputStream is = file.getObjectContent()) {
jsch.addIdentity("git", IOUtils.toByteArray(is), null, new byte[0]);
} catch (IOException | JSchException e) {
throw new IllegalArgumentException("Missing key file on s3: .ssh/id_rsa", e);
}
}
};
}
/**
* 抓遠端檔案然後存到本機 , 多筆
*
* @param user
* @param password
* @param addr
* @param port
* @param remoteFile
* @param localFile
* @throws JSchException
* @throws SftpException
* @throws Exception
*/
public static void get(String user, String password, String addr, int port,
List<String> remoteFile, List<String> localFile) throws JSchException, SftpException, Exception {
Session session = getSession(user, password, addr, port);
Channel channel = session.openChannel("sftp");
channel.connect();
ChannelSftp sftpChannel = (ChannelSftp) channel;
try {
for (int i=0; i<remoteFile.size(); i++) {
String rf=remoteFile.get(i);
String lf=localFile.get(i);
logger.info("get remote file: " + rf + " write to:" + lf );
sftpChannel.get(rf, lf);
File f=new File(lf);
if (!f.exists()) {
f=null;
logger.error("get remote file:"+rf + " fail!");
throw new Exception("get remote file:"+rf + " fail!");
}
f=null;
logger.info("success write:" + lf);
}
} catch (Exception e) {
e.printStackTrace();
throw e;
} finally {
sftpChannel.exit();
channel.disconnect();
session.disconnect();
}
}
/**
* Parses the keyFile hiding any Exceptions that might occur.
* @param keyFile the file.
* @return the "parsed" file.
*/
private static KeyPair parsePrivateKeyFile(File keyFile) {
if (keyFile == null) {
return null;
}
try {
JSch jsch = new JSch();
KeyPair key = KeyPair.load(jsch, keyFile.getAbsolutePath());
return key;
} catch (JSchException ex) {
return null;
}
}
@Test
public void testAsyncAuthSucceededAfterTimeout() throws Exception {
startServer(500);
authenticator = new PasswordAuthenticator() {
@Override
public boolean authenticate(String username, String password, ServerSession session) throws PasswordChangeRequiredException {
final AsyncAuth auth = new AsyncAuth();
new Thread() {
@Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException ignore) {
} finally {
auth.setAuthed(true);
}
}
}.start();
throw auth;
}
};
try {
authenticate();
} catch (JSchException e) {
assertTrue("Unexpected failure " + e.getMessage(), e.getMessage().startsWith("SSH_MSG_DISCONNECT"));
}
}
@Test
public void testConnectSessionEmpty() throws IOException, JSchException {
SFTPEnvironment env = new SFTPEnvironment();
Session session = mock(Session.class);
env.connect(session);
verify(session).connect();
verify(session).openChannel("sftp");
verifyNoMoreInteractions(session);
}
public static boolean checkForWrongCredentials(Throwable exception) {
if (exception.getCause() != null) {
return checkForWrongCredentials(exception.getCause());
} else {
String message = exception.getMessage();
return
exception instanceof SmbAuthException && message.contains("The specified network password is not correct") ||
exception instanceof JSchException && message.contains("Auth fail");
}
}
/**
* Create new channel every time a command needs to be executed. This is required to support execution of multiple
* commands in parallel. All created channels are cleaned up when the session is closed.
*
*
* @return a new {@link ChannelSftp}
* @throws SftpException
*/
public ChannelSftp getSftpChannel() throws SftpException {
try {
ChannelSftp channelSftp = (ChannelSftp) this.session.openChannel("sftp");
// In millsec
int connTimeout = state.getPropAsInt(SFTP_CONNECTION_TIMEOUT_KEY, DEFAULT_SFTP_CONNECTION_TIMEOUT);
channelSftp.connect(connTimeout);
return channelSftp;
} catch (JSchException e) {
throw new SftpException(0, "Cannot open a channel to SFTP server", e);
}
}
@Test
public void givenSameNameSizeDifferentDateOutputShouldNotBePresent() throws SftpException, RuntimeConfigurationException, JSchException, IOException {
when(jar1Server.getAttrs().getSize()).thenReturn(JAR1_SIZE * 10);
when(jar2Server.getAttrs().getSize()).thenReturn(JAR2_SIZE * 10);
when(jar1Server.getAttrs().getMtimeString()).thenReturn(new Date(JAR1_LAST_MODIFIED).toString());
when(jar2Server.getAttrs().getMtimeString()).thenReturn(new Date(JAR2_LAST_MODIFIED).toString());
List<File> files = classpathService.invokeFindDeployedJars(hostFiles, target);
assertEquals(files.size(), hostFiles.size());
}
/**
* Executes a command and returns the (standard) output through a StringBuilder.
*
* @param command The command
* @param output The output
* @return The exit code of the command
* @throws JSchException if a JSch error is detected.
* @throws FileSystemException if a session cannot be created.
* @throws IOException if an I/O error is detected.
*/
private int executeCommand(final String command, final StringBuilder output) throws JSchException, IOException {
final ChannelExec channel = (ChannelExec) getSession().openChannel("exec");
try {
channel.setCommand(command);
channel.setInputStream(null);
try (final InputStreamReader stream = new InputStreamReader(channel.getInputStream())) {
channel.setErrStream(System.err, true);
channel.connect(connectTimeoutMillis);
// Read the stream
final char[] buffer = new char[EXEC_BUFFER_SIZE];
int read;
while ((read = stream.read(buffer, 0, buffer.length)) >= 0) {
output.append(buffer, 0, read);
}
}
// Wait until the command finishes (should not be long since we read the output stream)
while (!channel.isClosed()) {
try {
Thread.sleep(SLEEP_MILLIS);
} catch (final Exception ee) {
// TODO: swallow exception, really?
}
}
} finally {
channel.disconnect();
}
return channel.getExitStatus();
}
@Override
protected JSch getJSch(OpenSshConfig.Host hc, FS fs) throws JSchException {
JSch jSch = super.getJSch(hc, fs);
jSch.removeAllIdentity();
if (!keyLocation.isEmpty())
jSch.addIdentity(keyLocation, password);
return jSch;
}
int write( UnixSshPath path, long startIndex, ByteBuffer bytes ) throws IOException {
try {
int bytesPosition = bytes.position();
// TODO cache this buffer for reuse
ByteBuffer temp = ByteBuffer.allocateDirect( bytes.limit() - bytesPosition );
temp.put( bytes );
bytes.position( bytesPosition );
String command = path.getFileSystem().getCommand( "dd" )
+ " conv=notrunc bs=1 seek=" + startIndex
+ " of=" + path.toAbsolutePath().quotedString();
ChannelExecWrapper sshChannel = null;
int written = 0;
try {
sshChannel = path.getFileSystem().getCommandRunner().open( command );
try (OutputStream out = sshChannel.getOutputStream()) {
WritableByteChannel outChannel = Channels.newChannel( out );
temp.flip();
written = outChannel.write( temp );
}
if ( written > 0 ) {
bytes.position( bytesPosition + written );
}
}
finally {
int exitCode = sshChannel.close();
if ( exitCode != 0 ) {
throw new IOException( "dd failed " + exitCode );
}
}
return written;
}
catch ( JSchException e ) {
throw new IOException( e );
}
}