I have a script (script1.sh) in a unix machine that calls a other script (script2.sh) in other unix remote machine:
ssh user#machine /opt/.../script2.sh param1 param2
There is a trust relationship between both machines.
If I run the script2, it works correctly, but if I run the script1, it calls script2 but JAVA_HOME of script2 is lost. I know that I can fix by "set JAVA_HOME" in script2 but I prefer other solution that I don´t have to put the specific path of JAVA_HOME in each scripts that is called by script1 (script2, script3,...)
Any idea?
Regards.
I didn´t find the solution so I tried other way. The other way is thought Java.
script1 calls a Java Application that is in the same machine. This Java Application connect with the other machine and calls script2 and catchs the response. The code would be:
//With Try catchs
//Create connection
JSch jSSH = new JSch();
Session session = jSSH.getSession(user, server, port);
UserInfo ui = new SessionUser(password, null);//SessionUser implements UserInfo
session.setUserInfo(ui);
session.setPassword(password);
session.connect();
//Create channel:
Channel channel = session.openChannel("shell");
//Configure inputs and outputs of channel:
OutputStream inputstream_for_the_channel = channel.getOutputStream();
PrintStream commander = new PrintStream(inputstream_for_the_channel, true);
channel.setOutputStream(null);
channel.connect(100);
//Command to execute
commander.println("cd /.../scriptFolder; ./script2.sh param1 param2; exit");
commander.flush();
//System.out.println(channel.getExitStatus());
InputStream outputstream_from_the_channel = channel.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(outputstream_from_the_channel));
String line = null;
//Catch and print the response with a StringBuilder
//close connection
channel.disconnect();
session.disconnect();
Related
I'm currently developping a failover service for an environment using Dynamics AX and 2 mirrored SQL servers, and I have some issues getting AX to work the way I expect it to.
I have developped a service which does the following :
- try to connect to the SQL servers instances
- start Dynamics AX using the reachable SQL server.
To do this, I have created 2 AX configuration files (.axc), each one pointing to a SQL server.
But when I try to start the service, no mater which way I use, AX always start using the configuration that is set using the AX server configuration tool.
Here are the command I've tried to start the AX service :
sc start AOS60$01 -regConfig=Config1
net start AOS60$01 /"-regConfig=Config1"
The service always start successfully, but doesn't care about the regConfig parameter.
As anybody an idea about how to solve this issue?
Regards,
Thomas T.
After looking for a while after a way to start the service with the -regConfig parameter, I finally gave up and developped a method which directly edit the Registry key holding the startup configuration value.
private void UpdateRegistry(string parameter)
{
RegistryKey key = Registry.LocalMachine.OpenSubKey("SYSTEM\\CurrentControlSet\\services\\Dynamics Server\\6.0\\01", true);
key.SetValue("Current", parameter, RegistryValueKind.String);
key.Close();
}
public void StartLocalServiceWithCLI(string serviceToStart, string parameter)
{
try
{
UpdateRegistry(parameter);
Process process = new System.Diagnostics.Process();
ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = string.Format("/C sc start {0} ", serviceToStart);
process.StartInfo = startInfo;
process.Start();
logger.WriteInfo(string.Format("Process {0} starting, parameters [{1}]", serviceToStart, parameter));
}
catch (Exception e)
{
logger.WriteError(string.Format("Error starting process {0}, parameters [{1}]\nError details :{2}", serviceToStart, parameter, e.Message));
}
}
I am writing a Java Program which could be able to send SMS using Kannel. I have Configured Kannel in my VM Vare Virtual Machine (Red Hat). Kannel is working fine and I can send SMS by typing the url
http://192.168.214.128:13013/cgi-bin/sendsms?
username=tester&password=foobar&to=03478847037&text=Mahtab
in my Windows browser. But when I access the same URL through Java Program
I am getting this exception
java.io.IOException: Server returned HTTP response code: 400` for URL:
http://192.168.214.128:13013/cgi-bin/sendsms?
username=tester&password=foobar&to=03478847037&text=Mahtab
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1245)
But when I paste the same url string in browser I am able to send the SMS.
code is attached
URL url = new URL("http://192.168.214.128:13013/cgi-bin/sendsms?username=tester&password=foobar&to=03478847037&text=Mahtab");
System.out.println(param.toString());
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
StringBuffer answer = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {answer.append(line);}
writer.close();
reader.close();
System.out.println(answer.toString());
Now please help me in this regard what I am missing???
I have solved this problem ............ actually code and every thing was right. The only problem was Netbeans. I had not cleaned the project when made some changes ...... that's why it was not giving the desired outcome ..... I cleaned the project and then build it... and I was successful so lesson learnt is that some time you are logically true but unfortunately your IDE is doing a little error which teases you the most.. #thor thanks for helping
I have created a flex app that uses sockets. I published the flex app in a web application that runs on glassfish server.
Now from that flex app i create a socket connection to a C# server and start sending/receiving data.
The problem is that after i create the socket connection to C# server the flex app first checks the policy file, and after it get's it, it closes the socket, without keep the connection alive.
This is my C# server:
TcpListener tcpListener = new TcpListener(IPAddress.Parse("172.17.41.211"), 12345);
TcpClient tcpclient = tcpListener.AcceptTcpClient();
Socket client = tcpclient.Client;
while (client.Available > 0)
{
int bytes = 0;
byte[] m_aBuffer = new byte[1024];
bytes = client.Receive(m_aBuffer, m_aBuffer.Length, SocketFlags.None);
String str = Encoding.ASCII.GetString(m_aBuffer, 0, bytes);
if (str.StartsWith("<policy-file-request/>"))
{
sendBytes = Encoding.ASCII.GetBytes("<cross-domain-policy><allow-access-from domain=\"172.17.41.211\" to-ports=\"12345\"/></cross-domain-policy>\0");
client.Send(sendBytes);
}
}
while (client.Connected)
{
Thread.Sleep(200);
sendBytes = Encoding.ASCII.GetBytes("message to client");
client.Send(sendBytes, sendBytes.Length, SocketFlags.None);
}
Now the flex client looks like:
private var socket:Socket = new Socket();
socket.addEventListener(Event.CONNECT, onConnect);
socket.addEventListener(Event.CLOSE, onClose);
socket.addEventListener(ProgressEvent.SOCKET_DATA, onData);
socket.addEventListener(ErrorEvent.ERROR, errorHandler);
socket.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR, errorHandler);
...
socket.connect("172.17.41.211", 12345);
...
Now after i create the connection and it gets the policy from server it closes this socket, so to be able to use this connection i have to call again
socket.connect("172.17.41.211", 12345));
After i do this, i can use normally the connection.
Can someone suggest why this happens and maybe is possible to not have closed the connection ?
You don't send the policy file through the socket itself. It needs to be on a different channel. For instance, if you connect to some ip/port, by default flash will try to connect to the same ip but on port 843 and look for the master policy file.
You can also set it manually using Security.loadPolicyFile(someURL). More information can be found here.
I am using the HTTP Connection in the following way:
HttpConnection _httpConnection = null;
try {
_httpConnection = (HttpConnection)Connector.open(_url);
} catch(Exception e) { }
byte [] postDataBytes = _postData.getBytes();
_httpConnection.setRequestMethod(HttpConnection.POST);
_httpConnection.setRequestProperty("User-Agent","Profile/MIDP-2.0 Configuration/CLDC-1.0");
_httpConnection.setRequestProperty("Content-Language", "en-US");
_httpConnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
_httpConnection.setRequestProperty("Connection", "close");
_httpConnection.setRequestProperty("Content-Length", Integer.toString(_postData.getBytes().length));
os = _httpConnection.openOutputStream();
os.write(postDataBytes);
os.flush();
This HTTP Connection requires parameters to successfully open. For example on a WIFI network, it requires the ";deviceside=true;interface=wifi" to be added to the URL.
The problem is for the EDGE connection. Each country requires different parameters to be added. For example in lebanon it requires ";deviceside=false" but in KSA if i add this parameter the connection will not open. In USA it needs different types of parametes. The question is how to establish an HTTP connection for all the countries with the same parameters. So that the application will successfully have an internet connection no matter where it is downloaded.
Welcome to the confusing world of network transports on BlackBerry! You will want to start with the article Connecting your BlackBerry - http and socket connections to the world.
Here is a simple example for "just give me a connection" (note, you will need to add appropriate error handling; also, myURL in the code below should have no connection descriptor info appended to it):
ConnectionFactory factory = new ConnectionFactory();
ConnectionDescriptor descriptor = factory.getConnection(myURL);
if (descriptor != null) {
_httpConnection = (HttpConnection) descriptor.getConnection();
...
}
Try using to use the method reffered in this link melick-rajee.blogspot.com and use it like
_url = "http://www.example.com";
_httpConnection = (HttpConnection)Connector.open(_url + getConnectionString());
You will have to sign the application to use this else the application will show exception.
To sign your application just go here Code Signing Keys
To use the connectionFactory, seems you need to set BisBOptions.
Try this:
connFact = new ConnectionFactory();
connFact.setTransportTypeOptions(TransportInfo.TRANSPORT_BIS_B,
new BisBOptions("mds-public"));
I am currently trying to build a threaded cleanup script with powershell, initiated from an IIS.
I have made a threaded "Kill process by owner" using powershell remoting, running from the same list of servers as my cleanup script, and that works no problem.
$jobs = #()
foreach ($comp in $comps) {
$jobs += start-job -FilePath ("CleanupJob.ps1") -ArgumentList $comp, $username
Write-Host "Started Job on: $comp"
}
foreach($job in $jobs)
{
$job | wait-job | out-null
receive-job $job.ID
}
Remove-Job -State Completed
When i run my script from the powershell console, the whole thing runs perfectly, main thread starts 28 new processes, which start a remoting connection to each server, and waits for all the jobs to finish. When they are finished, i get my output and the host thread exists. All running as planned.
Not so when I run it from my asp.net application, i get ""Started Job on: $comp"" for each of my 28 servers, but only a result from the first 14, and then the host thread just sits there. (untill i kill it with fire, and my output is returned to the asp.net webpage)
I have no way to see what happens in the script when i run it from the asp.net page.All i can see is cpu/ram usage drop to the same levels as when i run it from the PSconsole, but my main thread never closes. So I do believe the script works as supposed, but my webpage hangs untill the main thread closes(which it never does, as stated).
This is how I call my script (not the pretty .net <3 powershell way:)
public string RunProgramme(string scriptpath, string arguments)
{
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = #"powershell.exe";
startInfo.Arguments = "& \'"+scriptpath+"\' "+ arguments;
//return startInfo.Arguments;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;
Process process = new Process();
process.StartInfo = startInfo;
process.Start();
string output = process.StandardOutput.ReadToEnd();
string errors = process.StandardError.ReadToEnd();
return output;
}
The mystery deepens, added this line to my threaded jobs
Invoke-Command -Session $session -ScriptBlock {param($path) net send mymachine $path} -Args $msg
And when i run my script from the IIS, i receive message from each machine.
Just as my ram usage shows, all the jobs are run, but the output isnt returned properly, and my host thread just sits there...waiting...
As a note, you've got some unnecessary stuff going on.
foreach ($comp in $comps) {
start-job -FilePath ("CleanupJob.ps1") -ArgumentList $comp, $username
Write-Verbose "Started Job on: $comp"
}
Get-Job | Wait-Job | Out-Null
Remove-Job -State Completed
PowerShell already constructs a job list; there's no need to do so in a $jobs variable, and no need to enumerate them to do the wait.
Of course, you may use $jobs for something else in your code - but just wanted to make sure other folks see this alternative.
I found the solution. It's a deadlock caused by calling
string output = process.StandardOutput.ReadToEnd();
string errors = process.StandardError.ReadToEnd();
Right after each other.
Instead i followed http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.redirectstandarderror.aspx#Y95 and did this instead:
public string RunProgramme(string scriptpath, string arguments)
{
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = #"powershell.exe";
startInfo.Arguments = "& \'"+scriptpath+"\' "+ arguments;
startInfo.ErrorDialog = false;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;
Process process = new Process();
process.StartInfo = startInfo;
process.Start();
process.BeginErrorReadLine();
//Use BeginErrorReadLine on one of the streams to avoid the deadlock
//(i didnt need my error stream, but I did need to filter the errors from my output, so i did this)
string output = process.StandardOutput.ReadToEnd();
process.WaitForExit(1000 * 60);
return output;
}
No more hanging :)
you could use something like this to see the commands and the output...
$logfile = "C:\Documents and Settings\username\My Documents\WindowsPowerShell\logs\$(Get-Date -uformat "%Y%m%d - %H%M%S").log"
Start-Transcript -Path $logfile
I'm interested to know how you're calling it from ASP.Net as well?