Launch a script on remote ssh server using c# - c#

I have a GUI designed on Visual Studio using C#. I am a beginner in C# but good at C++ programming but due to requirements of task, I am designing it in C#. In this GUI, i have a button that connects to remote ssh server and as a trial, i have following commands to run when user presses button1.
client.Connect();
var output = client.RunCommand("echo happy test");
var dltOutput = client.RunCommand("rm /home/helloWorld.txt");
var launchFirst = client.RunCommand("bash /root/first.sh");
client.Disconnect();
Console.WriteLine(output.Result);
The command to delete "helloWorld.txt" in my home folder runs fine but could not running the command to run the shell script "first.sh". I would like to attach complete code below for your reference.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Renci.SshNet;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
//Connection information
string user = "root";
string pass = "hello123ado";
string host = "192.168.38.50";
int port = 22;
public Form1()
{
InitializeComponent();
}
private void Button1_Click(object sender, EventArgs e)
{
Console.WriteLine("Say Button1_Clicked");
using (var client = new SshClient(host,user,pass))
{
client.Connect();
var output = client.RunCommand("echo happy test");
var dltOutput = client.RunCommand("rm /home/helloWorld.txt");
var launchFirst = client.RunCommand("bash /root/first.sh");
client.Disconnect();
Console.WriteLine(output.Result);
}
}
private void Button2_Click(object sender, EventArgs e)
{
Console.WriteLine("Say Button2_Clicked");
}
private void Button3_Click(object sender, EventArgs e)
{
Console.WriteLine("Say Button3_Clicked");
}
}
}

Related

Update IP Address Text Box If There Is A Change To The Network

I'm trying to do something that is probably very simple, but I can't seem to get it working. I'm writing small app that displays some information including the IP Address. Everything is working perfectly, except that when the IP address changes (Network disconnect, LAN to WiFi, etc), I can't get it to update the text field with a message saying disconnected, or with the new IP Address. I've tried so many things and nothing works. A workaround that I am using is to shut the program down, and then start it immediately.
Here is the workaround code that I am using:
`
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Management.Automation;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Collections.ObjectModel;
using System.Runtime.InteropServices;
using System.Windows.Interop;
using System.Threading;
using Microsoft.Win32;
using System.Diagnostics;
using System.Xml.Linq;
using System.Net;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using Microsoft.TeamFoundation.Common.Internal;
using Microsoft.TeamFoundation.Framework.Common;
namespace JIC_BackgroundInfo
{
public partial class MainWindow : Window
{
private UserPreferenceChangedEventHandler UserPreferenceChanged;
public MainWindow()
{
InitializeComponent();
this.WindowStartupLocation = WindowStartupLocation.Manual;
this.Left = System.Windows.SystemParameters.WorkArea.Width - this.Width;
this.Top = System.Windows.SystemParameters.WorkArea.Height - this.Height;
NetworkChange.NetworkAddressChanged += new
NetworkAddressChangedEventHandler(AddressChangedCallback);
}
static void AddressChangedCallback(object sender, EventArgs e)
{
Process.Start(#"C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp\JIC_BackgroundInfo.exe");
Thread.Sleep(8500);
Application.Current.Shutdown();
}
`
I tried the following code, along with many other variations, but it just crashes the app:
`
public void AddressChangedCallback(object sender, EventArgs e)
{
using (PowerShell powerShell = PowerShell.Create())
{
try
{
var ps1 = $#"(Get-NetIPAddress -AddressFamily IPv4 -AddressState Preferred -PrefixOrigin Dhcp).IPv4Address";
powerShell.AddScript(ps1);
Collection<PSObject> PSOutput = powerShell.Invoke();
StringBuilder stringBuilder = new StringBuilder();
foreach (PSObject pSObject in PSOutput)
{
stringBuilder.AppendLine(pSObject.ToString());
}
TxtBoxIPAddress.Text = stringBuilder.ToString();
}
catch { TxtBoxIPAddress.Text = "No Address Found!"; return; }
}
}
`
Look into the ManagementEventWatcher class.
https://learn.microsoft.com/en-us/dotnet/api/system.management.managementeventwatcher?view=dotnet-plat-ext-7.0
You can use it to look for IP Addr changes and then ship those to your window that displays it.
private void AddressChangedCallback(object sender, EventArgs e)
{
Application.Current.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, (Action)delegate
{
using (PowerShell powerShell = PowerShell.Create())
{
try
{
var ps1 = $#"(Get-NetIPAddress -AddressFamily IPv4 -AddressState Preferred -PrefixOrigin Dhcp).IPv4Address";
powerShell.AddScript(ps1);
Collection<PSObject> PSOutput = powerShell.Invoke();
StringBuilder stringBuilder = new StringBuilder();
foreach (PSObject pSObject in PSOutput)
{
stringBuilder.AppendLine(pSObject.ToString());
}
TxtBoxIPAddress.Text = stringBuilder.ToString();
}
catch { TxtBoxIPAddress.Text = "No Address Found!"; }
}
});
}

Access to file denied in C# .NET 3.1 forms

Hello I was writing a basic text editor in C# on visual studio windows form using the .NET framework 3.1 long term support version everything worked fine until I wrote the save file script
Here's the code for "Form1.cs" which is where the open and save file functions reside
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Security.Principal;
namespace Text_Editor
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string locsave;
private void openbtn_Click(object sender, EventArgs e)
{
var identity = WindowsIdentity.GetCurrent();
var principal = new WindowsPrincipal(identity);
if (principal.IsInRole(WindowsBuiltInRole.Administrator) != true)
{
MessageBox.Show("Run as Admin");
System.Windows.Forms.Application.ExitThread();
}
else
{
OpenFileDialog openfile = new OpenFileDialog();
if (openfile.ShowDialog() == DialogResult.OK)
{
var locationArray = openfile.FileName;
string location = "";
locsave = locationArray;
foreach (char peice in locationArray)
{
location = location + peice;
}
var contentArray = File.ReadAllText(location);
string content = "";
label4.Text = location;
foreach (char peice in contentArray)
{
content = content + peice;
}
richTextBox1.Text = content;
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
Console.WriteLine("Test");
}
private void savebtn_Click(object sender, EventArgs e)
{
if (#label4.Text == "")
{
MessageBox.Show("Open a text file first");
}
else
{
StreamWriter outputfile = new StreamWriter(locsave);
outputfile.Write(richTextBox1.Text); //this is where the error occures and it throws the error of access denyed
outputfile.Close();
}
}
}
}
Does anyone have a suggestion about what to do I looked around on google for a solution but it seemed most did not work and some others I did not understand.

How to connect a gsm modem AUTOMATICALLY to available COM ports (without combobox)

THIS QUESTION MAY SEAM A DUPLICATE, BUT NOT. after a long period of search on internet and no, result, then had to seek for assistance.
All solutions apply to loading available ports in a combo box and the user checks one at a go. But the automation feature then dies.
thus, im looking for assistance on how the modem can connect automatically from the available ports without user interaction (USER FRIENDLINESS)
FOR THE COMBO BOX, IT IS WORKING FINE AS BELOW,
using GsmComm.GsmCommunication;
using GsmComm.PduConverter;
using GsmComm.Server;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace COMM_All
{
public partial class Comm_F : Form
{
public Comm_F()
{
InitializeComponent();
}
private void COM_PORTS()
{
string[] ports = SerialPort.GetPortNames();
txtGPort1.Items.AddRange(ports);
txtGPort2.Items.AddRange(ports);
}
private void Form1_Load(object sender, EventArgs e)
{
COM_PORTS();
}
private void Modem1_Click(object sender, EventArgs e)
{
if (txtGPort1.Text == "") { MessageBox.Show("Invalid Port Name"); return; }
comm = new GsmCommMain(txtGPort1.Text, 9600, 8);
Cursor.Current = Cursors.Default;
bool retry;
do
{
retry = false;
try
{
Cursor.Current = Cursors.WaitCursor; comm.Open(); Cursor.Current = Cursors.Default;
//MessageBox.Show("Modem Connected Sucessfully");
txtGStatus1.Text = "Connected Sucessfully";
comm.EnableMessageNotifications();
MessageBox.Show("Message notifications activated.");
}
catch (Exception)
{
Cursor.Current = Cursors.Default;
if (MessageBox.Show(this, "GSM Modem is not available", "Check",
MessageBoxButtons.RetryCancel, MessageBoxIcon.Warning) == DialogResult.Retry)
retry = true;
else { return; }
}
} while (retry);
}
}
}
Note: Computer has multiple usb devices;

Vlc.dotnet.form pause video with a button

I am hoping someone can help me in getting an issue of mine to work, I feel as if it is an easy one, however not having any luck in fixing what I am trying to do. I want to be able to pause a video which I am playing using vlc.dotnet below is a brief summary of the structure of my code.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Reflection;
using System.IO;
using Vlc.DotNet.Forms;
using System.Threading;
using Vlc.DotNet.Core;
using System.Diagnostics;
namespace TS1_C
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
button8.Click += new EventHandler(this.button8_Click);
}
void listBox1_MouseDoubleClick(object sender, MouseEventArgs e)
{
string chosen = listBox1.SelectedItem.ToString();
string final = selectedpath2 + "\\" + chosen; //Path
playfile(final);
}
void playfile(string final)
{
var control = new VlcControl();
var currentAssembly = Assembly.GetEntryAssembly();
var currentDirectory = new FileInfo(currentAssembly.Location).DirectoryName;
// Default installation path of VideoLAN.LibVLC.Windows
var libDirectory = new DirectoryInfo(Path.Combine(currentDirectory, "libvlc", IntPtr.Size == 4 ? "win-x86" : "win-x64"));
control.BeginInit();
control.VlcLibDirectory = libDirectory;
control.Dock = DockStyle.Fill;
control.EndInit();
panel1.Controls.Add(control);
control.Play();
}
private void button8_Click(object sender, EventArgs e)
{
}
}
}
As you can see I have one method which takes a double click from an item in a list box and plays it using the method playfile. However I want to be able to pause the video using my button known as button8. I have tried many things even this
control.Paused += new System.EventHandler<VlcMediaPlayerPausedEventArgs>(button8_Click);
Which I put into the playfile method, however nothing seems to work. I am wondering if my whole method in which I play a file using playfile(); is completely wrong. I am hoping someone can help me in trying to achieve what I need
Thank you
Your control should be initialized only once:
private VlcControl control;
public Form1()
{
InitializeComponent();
control = new VlcControl();
var currentAssembly = Assembly.GetEntryAssembly();
var currentDirectory = new FileInfo(currentAssembly.Location).DirectoryName;
// Default installation path of VideoLAN.LibVLC.Windows
var libDirectory = new DirectoryInfo(Path.Combine(currentDirectory, "libvlc", IntPtr.Size == 4 ? "win-x86" : "win-x64"));
control.BeginInit();
control.VlcLibDirectory = libDirectory;
control.Dock = DockStyle.Fill;
control.EndInit();
panel1.Controls.Add(control);
}
then, your play method could be simplified:
void playfile(string url)
{
control.Play(url);
}
And for your pause method:
private void button8_Click(object sender, EventArgs e)
{
control.Pause();
}

C# asp.net Disconnecting users terminal service session via loacl intranet

I have written code that uses a .bat file (code: rwvinstat /server:servername) that populates a DataGrid of users logged in to a terminal service session in c#. The .bat lives on the server with the app. files and will run properly if executed manually on the server .Also if i run the app. locally and call the .bat file on the server it works fine.
The problem is when i deploy my web app on the server the DataGrid never populates nor do i get any errors. i have given full permissions to IUSER_MACHINENAME(and various users) and i set the virtual directory permissions to read, run, execute. Ialso have set my web.conf fig to:< "identity impersonate="true" userName="username" password="password"/>
Here is my Source code:
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.IO;
public partial class ilsap01_users : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo("C:\\listUsersIlsap01.bat");
psi.RedirectStandardOutput = true;
psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
psi.UseShellExecute = false;
System.Diagnostics.Process listFiles;
listFiles = System.Diagnostics.Process.Start(psi);
System.IO.StreamReader rawUserData = listFiles.StandardOutput;
listFiles.WaitForExit(20000);
try
{
DataTable table2 = new DataTable();
table2.Columns.Add(new DataColumn("UserName", typeof(string)));
table2.Columns.Add(new DataColumn("SessionId", typeof(string)));
String myString = rawUserData.ReadToEnd();
string exp = #"([\w_]+)"; ;
MatchCollection matches = Regex.Matches(myString, exp, RegexOptions.IgnoreCase);
IEnumerator en = matches.GetEnumerator();
if (en.MoveNext())
{
while (en.MoveNext())
{
Match match = (Match)en.Current;
if (en.Current.ToString() == "rdpwd")
{
if (en.MoveNext())
{
if (en.Current.ToString() == "rdp")
{
en.MoveNext();
en.MoveNext();
en.MoveNext();
Match match_Item = (Match)en.Current;
string item = match_Item.Value;
en.MoveNext();
Match match_Item2 = (Match)en.Current;
string item2 = match_Item2.Value;
DataRow row = table2.NewRow();
row[0] = item.Split()[0];
row[1] = item2.Split()[0];
table2.Rows.Add(row);
}
}
}
}
}
this.displayUsers.DataSource = table2;
this.displayUsers.DataBind();
}
catch (Exception ex)
{
Response.Write(ex);
}
}
protected void dg_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void Button2_Click(object sender, EventArgs e)
{
Response.Redirect("ILSRF01_USERS.ASPX");
}
protected void Button1_Click(object sender, EventArgs e)
{
}
}
Is the executable that the batch file is calling (rwvinstat) in the system path? You might need to call it explicitly - c:\windows\system32\rwvinstat.exe or wherever it is located.
Did you grant the user the application pool is running as the appropriate Remote Desktop Services permissions?
Also, you might find the Cassia library a bit easier to use for your purposes.

Categories

Resources