using ssh.net im not able to getting output - c#

I'm not getting any output after running script. Please someone help me why the output is showing empty.
I can see its connecting to server.
namespace WebApplication10.helpers
{
public class service
{
public static List<Servicestatus> serviceadd(servername,UserName,Password)
{
List<Servicestatus> results = new List<Servicestatus>();
try
{
using (var client = new SshClient(servername, UserName, Password))
{
client.Connect();
SshCommand strOutput = client.CreateCommand("service --status-all");
var str = strOutput.Execute();
Console.WriteLine(str)
client.Disconnect();
}
}
catch (Exception e)
{
Console.WriteLine( e.Message );
}
}
}
}

You'll get the response with yourCommand.Result
SshCommand command = client.CreateCommand("service --status-all");
command.Execute();
Console.WriteLine(command.Result)

Related

What should I change so that Chrome not opens New Window every time when this code triggers

using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
using System;
using System.IO;
using System.Threading;
namespace TallyWhatsappsender
{
public class Class1
{
OpenQA.Selenium.IWebDriver chrome_driver = null;
public String InitProcess(String contact,String file_route,String title,String chrome_binary)
{
try
{
if (!System.IO.File.Exists(file_route))
{
return "Error : Attachment not found!";
}
if (!System.IO.File.Exists(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "chromedriver.exe")))
{
return "Error : Chromedriver.exe executable not found!\n chromedriver.exe file is missing\n update or reinstalling may fix the problem";
}
var chrome_driver_service = ChromeDriverService.CreateDefaultService(AppDomain.CurrentDomain.BaseDirectory, "chromedriver.exe");
chrome_driver_service.HideCommandPromptWindow = true;
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.UnhandledPromptBehavior = UnhandledPromptBehavior.Accept;
if (File.Exists(chrome_binary))
{
chromeOptions.BinaryLocation = chrome_binary;
}
chrome_driver = new ChromeDriver(chrome_driver_service, chromeOptions);
IJavaScriptExecutor javaScriptExecutor = (IJavaScriptExecutor)chrome_driver;
foreach (string ct in contact.Split(','))
{
if (string.IsNullOrEmpty(ct.Trim()))
{
break;
}
if(ct.Trim().Length != 12)
{
if (!(chrome_driver is null)) chrome_driver.Quit();
return "Error : Invalid contact number-" + ct;
}
chrome_driver.Url = "https://web.whatsapp.com/send?phone=" + ct.Trim();
try
{
chrome_driver.SwitchTo().Alert().Accept();
}
catch (NoAlertPresentException e1)
{
Console.WriteLine(e1.Message);
}
try
{
WebDriverWait wait = new WebDriverWait(chrome_driver, System.TimeSpan.FromSeconds(60));
wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.XPath("//*[#id='main']/footer/div[1]/div[2]/div/div[2]")));
}
catch (WebDriverTimeoutException)
{
continue;
}
//sending file
IWebElement file_open = chrome_driver.FindElement(By.XPath("//*[#id='main']/footer/div[1]/div[1]/div[2]/div/div/span"));
javaScriptExecutor.ExecuteScript("arguments[0].click();", file_open);
chrome_driver.FindElement(By.CssSelector("input[type='file']")).SendKeys(file_route);
WebDriverWait wait2 = new WebDriverWait(chrome_driver, System.TimeSpan.FromSeconds(30));
wait2.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.XPath("//*[#id='app']/div/div/div[2]/div[2]/span/div/span/div/div/div[2]/span/div/div/span")));
IWebElement file_send = chrome_driver.FindElement(By.XPath("//*[#id='app']/div/div/div[2]/div[2]/span/div/span/div/div/div[2]/span/div/div/span"));
javaScriptExecutor.ExecuteScript("arguments[0].click();", file_send);
Thread.Sleep(1000);
//sending text
IWebElement typebox = chrome_driver.FindElement(By.XPath("//*[#id='main']/footer/div[1]/div[2]/div/div[2]"));//:chrome_driver.FindElements(By.CssSelector("div[class ='_3u328 copyable-text selectable-text']"))[0];
typebox.SendKeys(title);
IWebElement text_send = chrome_driver.FindElement(By.XPath("//*[#id='main']/footer/div[1]/div[3]/button/span"));
javaScriptExecutor.ExecuteScript("arguments[0].click();", text_send);
Thread.Sleep(3000);
}
//chrome_driver.Quit();
return "Process finished";
}
//catch (Exception ex)
//{
// if (!(chrome_driver is null)) chrome_driver.Quit();
// return ex.Message;
//}
}
}
}
I am using the above code for exporting a PDF file from tally and send it through Whatsapp Automatically.
I am facing a problem :
Every time I use this option a new tab of chrome opens and closes after sending file, because of new window it asks me to login to whatsapp every time , I think it will sort out if it do not close after sending file or when I activate it , it goes automatically to the previously opened Web.Whatsapp.com so that I will not need authentication each time.
please help me out into this .
Thanks in advance
Every time you call chrome_driver = new ChromeDriver(chrome_driver_service, chromeOptions); a new tab opens.
Try separating the initiating process and the sending process.
For example, your InitProcess method could look like the following:
public InitProcess(String chrome_binary)
{
try
{
if (!System.IO.File.Exists(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "chromedriver.exe")))
{
return "Error : Chromedriver.exe executable not found!\n chromedriver.exe file is missing\n update or reinstalling may fix the problem";
}
var chrome_driver_service = ChromeDriverService.CreateDefaultService(AppDomain.CurrentDomain.BaseDirectory, "chromedriver.exe");
chrome_driver_service.HideCommandPromptWindow = true;
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.UnhandledPromptBehavior = UnhandledPromptBehavior.Accept;
if (File.Exists(chrome_binary))
{
chromeOptions.BinaryLocation = chrome_binary;
}
chrome_driver = new ChromeDriver(chrome_driver_service, chromeOptions);
return "Intiated";
}
}
And then you could add a Send function:
public String Send(String contact, String file_route, String title)
{
try
{
IJavaScriptExecutor javaScriptExecutor = (IJavaScriptExecutor)chrome_driver;
foreach (string ct in contact.Split(','))
{
if (string.IsNullOrEmpty(ct.Trim()))
{
break;
}
if(ct.Trim().Length != 12)
{
if (!(chrome_driver is null)) chrome_driver.Quit();
return "Error : Invalid contact number-" + ct;
}
chrome_driver.Url = "https://web.whatsapp.com/send?phone=" + ct.Trim();
try
{
chrome_driver.SwitchTo().Alert().Accept();
}
catch (NoAlertPresentException e1)
{
Console.WriteLine(e1.Message);
}
try
{
WebDriverWait wait = new WebDriverWait(chrome_driver, System.TimeSpan.FromSeconds(60));
wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.XPath("//*[#id='main']/footer/div[1]/div[2]/div/div[2]")));
}
catch (WebDriverTimeoutException)
{
continue;
}
//sending file
IWebElement file_open = chrome_driver.FindElement(By.XPath("//*[#id='main']/footer/div[1]/div[1]/div[2]/div/div/span"));
javaScriptExecutor.ExecuteScript("arguments[0].click();", file_open);
chrome_driver.FindElement(By.CssSelector("input[type='file']")).SendKeys(file_route);
WebDriverWait wait2 = new WebDriverWait(chrome_driver, System.TimeSpan.FromSeconds(30));
wait2.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.XPath("//*[#id='app']/div/div/div[2]/div[2]/span/div/span/div/div/div[2]/span/div/div/span")));
IWebElement file_send = chrome_driver.FindElement(By.XPath("//*[#id='app']/div/div/div[2]/div[2]/span/div/span/div/div/div[2]/span/div/div/span"));
javaScriptExecutor.ExecuteScript("arguments[0].click();", file_send);
Thread.Sleep(1000);
//sending text
IWebElement typebox = chrome_driver.FindElement(By.XPath("//*[#id='main']/footer/div[1]/div[2]/div/div[2]"));//:chrome_driver.FindElements(By.CssSelector("div[class ='_3u328 copyable-text selectable-text']"))[0];
typebox.SendKeys(title);
IWebElement text_send = chrome_driver.FindElement(By.XPath("//*[#id='main']/footer/div[1]/div[3]/button/span"));
javaScriptExecutor.ExecuteScript("arguments[0].click();", text_send);
Thread.Sleep(3000);
return "Process finished";
}
}
}
Now you call InitProcess only once at the beginning of you program and Send every time you want to send the file.

How to check if remote database MYSQL is available

I need register the user access on my webpage aspx in MySQL remote Database.
But this MySQL remote Database it could be unavailable.
I have tried this code, but how to execute the RegisterUSer() method in the bool IsServerConnected() method ?
public bool IsServerConnected()
{
using (var l_oConnection =
new OdbcConnection(ConfigurationManager.ConnectionStrings["ConnMySQL"].ConnectionString))
{
try
{
l_oConnection.Open();
return true;
}
catch (OdbcException)
{
return false;
}
}
}
private void RegisterUSer()
{
using (OdbcConnection myConnectionString =
new OdbcConnection(ConfigurationManager.ConnectionStrings["ConnMySQL"].ConnectionString))
{
string sql = #String.Format(" INSERT IGNORE INTO tbl_user ");
sql += String.Format(" ... ");
using (OdbcCommand command =
new OdbcCommand(sql, myConnectionString))
{
try
{
command.Connection.Open();
command.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
command.Connection.Close();
}
}
#Edit 01
Error :
The type or namespace name 'resultType' could not be found (are you
missing a using directive or an assembly reference?)
You could just do a "wrapper" method that calls first to IsServerConnected() and depending on the returned boolean then calls RegisterUSer() or throws an error if the database is not availiable.
Quick and dirty pseudocode
private resultType ChickenWrapMethod()
{
if (!IsServerConnected())
{
//Throw some error here and exit
}
RegisterUSer()
}
BTW...in my opinion you should consider opening the sql connection out of the methods so it can be shared by both operations
Try this in c#. I hope I was helpful.
using System.Net.NetworkInformation;
var ping = new Ping();
var reply = ping.Send("XX.XX.XX.XXX", 60 * 1000); // 1 minute time out (in ms)
if (reply.Status == IPStatus.Success)
{
Response.Write("Server XX.XX.XX.XXX is up");
RegisterUSer();
}
else
{
Response.Write("Server XX.XX.XX.XXX is down");
}

Displaying Output from SSH.NET

I am fairly new with C# and I am trying to write an SSH console application using the SSH.NET framework. So far I was able to connect to my server successfully, but now I am trying to run commands and have it display the result. Yet, my console comes out blank when I run my application. My end goal was to execute a set of commands and see the results at the end of it.
Program.cs
using Renci.SshNet;
class Program
{
//Login Parameter
const String Hostname = "somePort";
const int PortNumber = 22;
const String Username = "username";
const String Password = "root";
static void Main(string[] args)
{
//Bypass Keyboard authentication
KeyboardInteractiveAuthenticationMethod kauth = new KeyboardInteractiveAuthenticationMethod(Username);
PasswordAuthenticationMethod pauth = new PasswordAuthenticationMethod(Username, Password);
kauth.AuthenticationPrompt += new EventHandler<Renci.SshNet.Common.AuthenticationPromptEventArgs>(HandleKeyEvent);
//Grab info for connections
ConnectionInfo connectionInfo = new ConnectionInfo(Hostname, PortNumber, Username, pauth, kauth);
//Connect
using (SshClient client = new SshClient(connectionInfo))
{
try
{
//Connect to server
client.Connect();
Console.WriteLine("Connection successful");
var command = client.CreateCommand("ls");
var result = command.Execute();
command.Execute();
Console.WriteLine(result);
//Disconnect from server
client.Disconnect();
}
//Show exp message
catch (Exception exp)
{
throw exp;
}
}
}
//Handle two step auth
static void HandleKeyEvent(Object sender, Renci.SshNet.Common.AuthenticationPromptEventArgs e)
{
foreach (Renci.SshNet.Common.AuthenticationPrompt prompt in e.Prompts)
{
if (prompt.Request.IndexOf("Password:", StringComparison.InvariantCultureIgnoreCase) != -1)
{
prompt.Response = Password;
}
}
}
}
I don't know if you have resolved this issue yet, but the solution is simple in this case.
The function:
command.Execute()
doesn't return your result.
You have to execute like you did, but then grab the result via
command.Result
It would look something like this:
var command = client.CreateCommand("ls");
command.Execute();
var result = command.Result;
Hope i could help you.

signalr .net client reconnect error

I'm writing a program that makes remote desktop connection with signalr. I keep sending screenshots (in the .net client) for it. But when I reconnect to the server after a while, I get error: Connection started reconnecting before invocation result was received.
public void ImageMain()
{
var querstring = new Dictionary<string, string>();
querstring.Add("userid", "sessionlocal");
var hubConnectionMouse = new HubConnection("http://localhost:8089/", querstring);
Program p = new Program();
IHubProxy myHubProxyMouse = hubConnectionMouse.CreateHubProxy("MyHub");
string a = "";
try
{
hubConnectionMouse.Start().Wait();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
byte[] ekran;
while (true)
{
ekran = null;
ekran = EkranGoruntusu();
if (ekran.Length < 80000)
{
try
{
myHubProxy.Invoke("addMessage", "sessionlocal", ekran).ContinueWith(task =>
{
if (task.IsFaulted)
{
Console.WriteLine("!!! image gönderilirken hata olıştu:{0} \n",
task.Exception.GetBaseException() + "tekrar bağlanılıyor....");
}
else
{
Console.WriteLine("Add messgae" + " gonderilecek ekran boyutu " + ekran.Length);
Console.WriteLine("hub durumu" + hubConnection.State);
}
}).Wait();
}
catch (Exception exception)
{
Console.WriteLine("bağlantı hatas tekrar bağlanılıyor" + exception.Message);
Console.ReadKey();
}
}
else
{
Console.WriteLine("gonderilcek goruntü cok büyük");
}
}
Console.ReadLine();
}

IRCBot C# connection issues

I am having an issue with my IRC Bot I am trying to write in c# just as a way to help get my head around the IRC protocol, I am planning on writing a client/server in the future but as you can prolly guess I am far off this :P
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.IO;
namespace LolBot
{
struct IRCConfig
{
public string server;
public int port;
public string nick;
public string name;
}
class IRCBot
{
TcpClient IRCConnection = null;
IRCConfig config;
NetworkStream ns = null;
StreamReader sr = null;
StreamWriter sw = null;
public IRCBot(IRCConfig config)
{
this.config = config;
try
{
IRCConnection = new TcpClient(config.server, config.port);
}
catch
{
Console.WriteLine("Connection Error");
}
try
{
ns = IRCConnection.GetStream();
sr = new StreamReader(ns);
sw = new StreamWriter(ns);
sendData("USER", config.nick + config.name);
sendData("NICK", config.nick);
}
catch
{
Console.WriteLine("Communication error");
}
finally
{
if (sr != null)
sr.Close();
if (sw != null)
sw.Close();
if (ns != null)
ns.Close();
if (IRCConnection != null)
IRCConnection.Close();
}
}
public void sendData(string cmd, string param)
{
if (param == null)
{
sw.WriteLine(cmd);
sw.Flush();
Console.WriteLine(cmd);
}
else
{
sw.WriteLine(cmd + " " + param);
sw.Flush();
Console.WriteLine(cmd + " " + param);
}
}
public void IRCWork()
{
string[] ex;
string data;
bool shouldRun = true;
while (shouldRun)
{
data = sr.ReadLine();
Console.WriteLine(data);
char[] charSeparator = new char[] { ' ' };
ex = data.Split(charSeparator, 5);
if (ex[0] == "PING")
{
sendData("PONG", ex[1]);
}
if (ex.Length > 4) //is the command received long enough to be a bot command?
{
string command = ex[3]; //grab the command sent
switch (command)
{
case ":!join":
sendData("JOIN", ex[4]); //if the command is !join send the "JOIN" command to the server with the parameters set by the user
break;
case ":!say":
sendData("PRIVMSG", ex[2] + " " + ex[4]); //if the command is !say, send a message to the chan (ex[2]) followed by the actual message (ex[4]).
break;
case ":!quit":
sendData("QUIT", ex[4]); //if the command is quit, send the QUIT command to the server with a quit message
shouldRun = false; //turn shouldRun to false - the server will stop sending us data so trying to read it will not work and result in an error. This stops the loop from running and we will close off the connections properly
break;
}
}
}
}
}
class Program
{
static void Main(string[] args)
{
IRCConfig conf = new IRCConfig();
conf.name = "LolBot";
conf.nick = "LolBot";
conf.port = 6667;
conf.server = "irc.strictfp.com";
new IRCBot(conf);
Console.WriteLine("Bot quit/crashed");
Console.ReadLine();
}
}
}
Whenever I execute the Bot, it comes up with:
USER AspiBot google.com google.com :AspiBot
NICK AspiBot
Bot quit/crashed
I don't really understand why it is quiting before connecting to the server and I am also looking on how to set it up to join a channel, I am aware that I need to use JOIN but I'm not sure how to implent it.
You should probably not do so much in the constructor, but the problem you are encountering here is that you are not calling IRCWork() after newing up the bot.
var bot = new IRCBot(conf);
bot.IRCWork();
EDIT You are also closing all of your connections in the finally block of your constructor, so IRCWork() isn't going to work anyway. Try implementing IDisposable, and putting your close logic in Dispose():
using (var bot = new IRCBot(conf))
{
bot.IRCWork();
}
Quick refactor of posted code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.IO;
namespace LolBot
{
internal struct IRCConfig
{
public string server;
public int port;
public string nick;
public string name;
}
internal class IRCBot : IDisposable
{
private TcpClient IRCConnection = null;
private IRCConfig config;
private NetworkStream ns = null;
private StreamReader sr = null;
private StreamWriter sw = null;
public IRCBot(IRCConfig config)
{
this.config = config;
}
public void Connect()
{
try
{
IRCConnection = new TcpClient(config.server, config.port);
}
catch
{
Console.WriteLine("Connection Error");
throw;
}
try
{
ns = IRCConnection.GetStream();
sr = new StreamReader(ns);
sw = new StreamWriter(ns);
sendData("USER", config.nick + config.name);
sendData("NICK", config.nick);
}
catch
{
Console.WriteLine("Communication error");
throw;
}
}
public void sendData(string cmd, string param)
{
if (param == null)
{
sw.WriteLine(cmd);
sw.Flush();
Console.WriteLine(cmd);
}
else
{
sw.WriteLine(cmd + " " + param);
sw.Flush();
Console.WriteLine(cmd + " " + param);
}
}
public void IRCWork()
{
string[] ex;
string data;
bool shouldRun = true;
while (shouldRun)
{
data = sr.ReadLine();
Console.WriteLine(data);
char[] charSeparator = new char[] {' '};
ex = data.Split(charSeparator, 5);
if (ex[0] == "PING")
{
sendData("PONG", ex[1]);
}
if (ex.Length > 4) //is the command received long enough to be a bot command?
{
string command = ex[3]; //grab the command sent
switch (command)
{
case ":!join":
sendData("JOIN", ex[4]);
//if the command is !join send the "JOIN" command to the server with the parameters set by the user
break;
case ":!say":
sendData("PRIVMSG", ex[2] + " " + ex[4]);
//if the command is !say, send a message to the chan (ex[2]) followed by the actual message (ex[4]).
break;
case ":!quit":
sendData("QUIT", ex[4]);
//if the command is quit, send the QUIT command to the server with a quit message
shouldRun = false;
//turn shouldRun to false - the server will stop sending us data so trying to read it will not work and result in an error. This stops the loop from running and we will close off the connections properly
break;
}
}
}
}
public void Dispose()
{
if (sr != null)
sr.Close();
if (sw != null)
sw.Close();
if (ns != null)
ns.Close();
if (IRCConnection != null)
IRCConnection.Close();
}
}
internal class Program
{
private static void Main(string[] args)
{
IRCConfig conf = new IRCConfig();
conf.name = "LolBot";
conf.nick = "LolBot";
conf.port = 6667;
conf.server = "irc.strictfp.com";
using (var bot = new IRCBot(conf))
{
bot.Connect();
bot.IRCWork();
}
Console.WriteLine("Bot quit/crashed");
Console.ReadLine();
}
}
}

Categories