List of usage examples for org.apache.commons.io.output NullOutputStream write
public void write(byte[] b) throws IOException
/dev/null
. From source file:com.github.vatbub.awsvpnlauncher.Main.java
/** * Connects to the specified instance using ssh. Output will be sent to System.out, input will be taken from System.in * * @param instanceID The id of the instance to connect to *//*from w ww. j a va 2 s .c om*/ private static void ssh(String instanceID) { try { File privateKey = new File(prefs.getPreference(Property.privateKeyFile)); DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest(); List<String> instanceId = new ArrayList<>(1); instanceId.add(instanceID); describeInstancesRequest.setInstanceIds(instanceId); DescribeInstancesResult describeInstancesResult = client.describeInstances(describeInstancesRequest); Instance instance = describeInstancesResult.getReservations().get(0).getInstances().get(0); String sshIp = instance.getPublicDnsName(); // SSH config FOKLogger.info(Main.class.getName(), "Configuring SSH..."); Properties sshConfig = new Properties(); sshConfig.put("StrictHostKeyChecking", "no"); JSch jsch = new JSch(); jsch.addIdentity(privateKey.getAbsolutePath()); FOKLogger.info(Main.class.getName(), "Connecting using ssh to " + sshUsername + "@" + sshIp); session = jsch.getSession(sshUsername, sshIp, 22); session.setConfig(sshConfig); try { session.connect(); } catch (Exception e) { FOKLogger.log(Main.class.getName(), Level.SEVERE, "Could not connect to the instance due to an exception", e); } // Connected FOKLogger.info(Main.class.getName(), "Connection established, connected to " + sshUsername + "@" + sshIp); Channel channel = session.openChannel("shell"); if (posix.isatty(FileDescriptor.out)) { FOKLogger.info(Main.class.getName(), "Connected to a tty, disabling colors..."); // Disable colors ((ChannelShell) channel).setPtyType("vt102"); } channel.setInputStream(copyAndFilterInputStream()); channel.setOutputStream(new MyPrintStream()); channel.connect(); NullOutputStream nullOutputStream = new NullOutputStream(); Thread watchForSSHDisconnectThread = new Thread(() -> { while (channel.isConnected()) { nullOutputStream.write(0); } // disconnected System.exit(0); }); watchForSSHDisconnectThread.setName("watchForSSHDisconnectThread"); watchForSSHDisconnectThread.start(); } catch (JSchException | IOException e) { FOKLogger.log(Main.class.getName(), Level.SEVERE, "An error occurred", e); } }
From source file:com.github.vatbub.awsvpnlauncher.Main.java
/** * Launches a new VPN server on AWS EC2 if everything is configured * * @see PropertyNotConfiguredException/*from ww w . j av a2 s . co m*/ * @see #terminate() */ private static void launch() { File privateKey = new File(prefs.getPreference(Property.privateKeyFile)); vpnPassword = prefs.getPreference(Property.openvpnPassword); if (!privateKey.exists() && !privateKey.isFile()) { throw new IllegalArgumentException("The file specified as " + Property.privateKeyFile.toString() + " does not exist or is not a file."); } FOKLogger.info(Main.class.getName(), "Preparing..."); try { // Check if our security group exists already FOKLogger.info(Main.class.getName(), "Checking for the required security group..."); DescribeSecurityGroupsRequest describeSecurityGroupsRequest = new DescribeSecurityGroupsRequest() .withGroupNames(securityGroupName); List<String> securityGroups = new ArrayList<>(); boolean created = false; // will become true if the security group had to be created to avoid duplicate logs String securityGroupId; try { DescribeSecurityGroupsResult describeSecurityGroupsResult = client .describeSecurityGroups(describeSecurityGroupsRequest); securityGroupId = describeSecurityGroupsResult.getSecurityGroups().get(0).getGroupId(); } catch (AmazonEC2Exception e) { // Security group does not exist, create the security group created = true; FOKLogger.info(Main.class.getName(), "Creating the required security group..."); CreateSecurityGroupRequest createSecurityGroupRequest = new CreateSecurityGroupRequest() .withGroupName(securityGroupName).withDescription( "This security group was automatically created to run a OpenVPN Access Server."); CreateSecurityGroupResult createSecurityGroupResult = client .createSecurityGroup(createSecurityGroupRequest); securityGroupId = createSecurityGroupResult.getGroupId(); IpRange ipRange = new IpRange().withCidrIp("0.0.0.0/0"); IpPermission sshPermission1 = new IpPermission().withIpv4Ranges(ipRange).withIpProtocol("tcp") .withFromPort(22).withToPort(22); IpPermission sshPermission2 = new IpPermission().withIpv4Ranges(ipRange).withIpProtocol("tcp") .withFromPort(943).withToPort(943); IpPermission httpsPermission1 = new IpPermission().withIpv4Ranges(ipRange).withIpProtocol("tcp") .withFromPort(443).withToPort(443); IpPermission httpsPermission2 = new IpPermission().withIpv4Ranges(ipRange).withIpProtocol("udp") .withFromPort(1194).withToPort(1194); AuthorizeSecurityGroupIngressRequest authorizeSecurityGroupIngressRequest = new AuthorizeSecurityGroupIngressRequest() .withGroupName(securityGroupName).withIpPermissions(sshPermission1) .withIpPermissions(sshPermission2).withIpPermissions(httpsPermission1) .withIpPermissions(httpsPermission2); // retry while the security group is not yet ready int retries = 0; long lastPollTime = System.currentTimeMillis(); boolean requestIsFailing = true; do { // we're waiting if (System.currentTimeMillis() - lastPollTime >= Math.pow(2, retries) * 100) { retries = retries + 1; lastPollTime = System.currentTimeMillis(); try { client.authorizeSecurityGroupIngress(authorizeSecurityGroupIngressRequest); // no exception => we made it requestIsFailing = false; } catch (AmazonEC2Exception e2) { FOKLogger.info(Main.class.getName(), "Still waiting for the security group to be created, api error message is currently: " + e2.getMessage()); requestIsFailing = true; } } } while (requestIsFailing); FOKLogger.info(Main.class.getName(), "The required security group has been successfully created!"); } if (!created) { FOKLogger.info(Main.class.getName(), "The required security group already exists, we can continue"); } securityGroups.add(securityGroupId); securityGroups.add(securityGroupId); FOKLogger.info(Main.class.getName(), "Creating the RunInstanceRequest..."); RunInstancesRequest request = new RunInstancesRequest(getAmiId(awsRegion), 1, 1); request.setInstanceType(InstanceType.T2Micro); request.setKeyName(prefs.getPreference(Property.awsKeyPairName)); request.setSecurityGroupIds(securityGroups); FOKLogger.info(Main.class.getName(), "Starting the EC2 instance..."); RunInstancesResult result = client.runInstances(request); List<Instance> instances = result.getReservation().getInstances(); // SSH config FOKLogger.info(Main.class.getName(), "Configuring SSH..."); Properties sshConfig = new Properties(); sshConfig.put("StrictHostKeyChecking", "no"); JSch jsch = new JSch(); jsch.addIdentity(privateKey.getAbsolutePath()); int retries = 0; for (Instance instance : instances) { // write the instance id to a properties file to be able to terminate it later on again prefs.reload(); if (prefs.getPreference("instanceIDs", "").equals("")) { prefs.setPreference("instanceIDs", instance.getInstanceId()); } else { prefs.setPreference("instanceIDs", prefs.getPreference("instanceIDs", "") + ";" + instance.getInstanceId()); } // Connect to the instance using ssh FOKLogger.info(Main.class.getName(), "Waiting for the instance to boot..."); long lastPrintTime = System.currentTimeMillis(); DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest(); List<String> instanceId = new ArrayList<>(1); instanceId.add(instance.getInstanceId()); describeInstancesRequest.setInstanceIds(instanceId); DescribeInstancesResult describeInstancesResult; newInstance = instance; do { // we're waiting if (System.currentTimeMillis() - lastPrintTime >= Math.pow(2, retries) * 100) { retries = retries + 1; describeInstancesResult = client.describeInstances(describeInstancesRequest); newInstance = describeInstancesResult.getReservations().get(0).getInstances().get(0); lastPrintTime = System.currentTimeMillis(); if (newInstance.getState().getCode() != 16) { FOKLogger.info(Main.class.getName(), "Still waiting for the instance to boot, current instance state is " + newInstance.getState().getName()); } } } while (newInstance.getState().getCode() != 16); FOKLogger.info(Main.class.getName(), "Instance is " + newInstance.getState().getName()); // generate the ssh ip of the instance String sshIp = newInstance.getPublicDnsName(); FOKLogger.info(Main.class.getName(), "The instance id is " + newInstance.getInstanceId()); FOKLogger.info(Main.class.getName(), "The instance ip is " + newInstance.getPublicIpAddress()); FOKLogger.info(Main.class.getName(), "Connecting using ssh to " + sshUsername + "@" + sshIp); FOKLogger.info(Main.class.getName(), "The instance will need some time to configure ssh on its end so some connection timeouts are normal"); boolean retry; session = jsch.getSession(sshUsername, sshIp, 22); session.setConfig(sshConfig); do { try { session.connect(); retry = false; } catch (Exception e) { FOKLogger.info(Main.class.getName(), e.getClass().getName() + ": " + e.getMessage() + ", retrying, Press Ctrl+C to cancel"); retry = true; } } while (retry); FOKLogger.info(Main.class.getName(), "----------------------------------------------------------------------"); FOKLogger.info(Main.class.getName(), "The following is the out- and input of the ssh session."); FOKLogger.info(Main.class.getName(), "Please note that out- and input may appear out of sync."); FOKLogger.info(Main.class.getName(), "----------------------------------------------------------------------"); PipedInputStream sshIn = new PipedInputStream(); PipedOutputStream sshIn2 = new PipedOutputStream(sshIn); PrintStream sshInCommandStream = new PrintStream(sshIn2); Channel channel = session.openChannel("shell"); channel.setInputStream(sshIn); channel.setOutputStream(new MyPrintStream()); channel.connect(); sshInCommandStream.print("yes\n"); sshInCommandStream.print("yes\n"); sshInCommandStream.print("1\n"); sshInCommandStream.print("\n"); sshInCommandStream.print("\n"); sshInCommandStream.print("yes\n"); sshInCommandStream.print("yes\n"); sshInCommandStream.print("\n"); sshInCommandStream.print("\n"); sshInCommandStream.print("\n"); sshInCommandStream.print("\n"); sshInCommandStream.print("echo \"" + adminUsername + ":" + vpnPassword + "\" | sudo chpasswd\n"); sshInCommandStream.print("exit\n"); NullOutputStream nullOutputStream = new NullOutputStream(); Thread watchForSSHDisconnectThread = new Thread(() -> { while (channel.isConnected()) { nullOutputStream.write(0); } // disconnected cont(); }); watchForSSHDisconnectThread.setName("watchForSSHDisconnectThread"); watchForSSHDisconnectThread.start(); } } catch (JSchException | IOException e) { e.printStackTrace(); if (session != null) { session.disconnect(); } System.exit(1); } }