Option to run Racadm locally; handle: logs, exceptions. Separate folders for scripts, logs

This commit is contained in:
2026-01-16 16:21:05 +00:00
parent ecec60554f
commit 803934721f
5 changed files with 1064 additions and 892 deletions

View File

@@ -5,7 +5,7 @@
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{73DED4CD-B2B1-491E-87B7-BC1F11759C53}</ProjectGuid> <ProjectGuid>{73DED4CD-B2B1-491E-87B7-BC1F11759C53}</ProjectGuid>
<OutputType>Exe</OutputType> <OutputType>WinExe</OutputType>
<RootNamespace>SSH_Test</RootNamespace> <RootNamespace>SSH_Test</RootNamespace>
<AssemblyName>SSH_Test</AssemblyName> <AssemblyName>SSH_Test</AssemblyName>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion> <TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
@@ -15,7 +15,7 @@
<IsWebBootstrapper>false</IsWebBootstrapper> <IsWebBootstrapper>false</IsWebBootstrapper>
<NuGetPackageImportStamp> <NuGetPackageImportStamp>
</NuGetPackageImportStamp> </NuGetPackageImportStamp>
<PublishUrl>publish\</PublishUrl> <PublishUrl>D:\Shared\VS\</PublishUrl>
<Install>true</Install> <Install>true</Install>
<InstallFrom>Disk</InstallFrom> <InstallFrom>Disk</InstallFrom>
<UpdateEnabled>false</UpdateEnabled> <UpdateEnabled>false</UpdateEnabled>
@@ -28,6 +28,7 @@
<ApplicationRevision>0</ApplicationRevision> <ApplicationRevision>0</ApplicationRevision>
<ApplicationVersion>1.0.0.%2a</ApplicationVersion> <ApplicationVersion>1.0.0.%2a</ApplicationVersion>
<UseApplicationTrust>false</UseApplicationTrust> <UseApplicationTrust>false</UseApplicationTrust>
<PublishWizardCompleted>true</PublishWizardCompleted>
<BootstrapperEnabled>true</BootstrapperEnabled> <BootstrapperEnabled>true</BootstrapperEnabled>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
@@ -52,10 +53,31 @@
<PropertyGroup> <PropertyGroup>
<StartupObject /> <StartupObject />
</PropertyGroup> </PropertyGroup>
<PropertyGroup>
<TargetZone>LocalIntranet</TargetZone>
</PropertyGroup>
<PropertyGroup>
<GenerateManifests>false</GenerateManifests>
</PropertyGroup>
<PropertyGroup>
<ApplicationManifest>Properties\app.manifest</ApplicationManifest>
</PropertyGroup>
<PropertyGroup>
<ManifestCertificateThumbprint>4A871742B5537E7E2FE907BD60809E3A6E6EEDBF</ManifestCertificateThumbprint>
</PropertyGroup>
<PropertyGroup>
<ManifestKeyFile>SSH_Test_TemporaryKey.pfx</ManifestKeyFile>
</PropertyGroup>
<PropertyGroup>
<SignManifests>true</SignManifests>
</PropertyGroup>
<ItemGroup> <ItemGroup>
<Reference Include="BouncyCastle.Cryptography, Version=2.0.0.0, Culture=neutral, PublicKeyToken=072edcf4a5328938, processorArchitecture=MSIL"> <Reference Include="BouncyCastle.Cryptography, Version=2.0.0.0, Culture=neutral, PublicKeyToken=072edcf4a5328938, processorArchitecture=MSIL">
<HintPath>packages\BouncyCastle.Cryptography.2.6.2\lib\net461\BouncyCastle.Cryptography.dll</HintPath> <HintPath>packages\BouncyCastle.Cryptography.2.6.2\lib\net461\BouncyCastle.Cryptography.dll</HintPath>
</Reference> </Reference>
<Reference Include="log4net, Version=3.2.0.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL">
<HintPath>packages\log4net.3.2.0\lib\net462\log4net.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Bcl.AsyncInterfaces, Version=10.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL"> <Reference Include="Microsoft.Bcl.AsyncInterfaces, Version=10.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>packages\Microsoft.Bcl.AsyncInterfaces.10.0.0\lib\net462\Microsoft.Bcl.AsyncInterfaces.dll</HintPath> <HintPath>packages\Microsoft.Bcl.AsyncInterfaces.10.0.0\lib\net462\Microsoft.Bcl.AsyncInterfaces.dll</HintPath>
</Reference> </Reference>
@@ -72,6 +94,7 @@
<Reference Include="System.Buffers, Version=4.0.5.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL"> <Reference Include="System.Buffers, Version=4.0.5.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>packages\System.Buffers.4.6.1\lib\net462\System.Buffers.dll</HintPath> <HintPath>packages\System.Buffers.4.6.1\lib\net462\System.Buffers.dll</HintPath>
</Reference> </Reference>
<Reference Include="System.Configuration" />
<Reference Include="System.Core" /> <Reference Include="System.Core" />
<Reference Include="System.Formats.Asn1, Version=8.0.0.2, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL"> <Reference Include="System.Formats.Asn1, Version=8.0.0.2, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>packages\System.Formats.Asn1.8.0.2\lib\net462\System.Formats.Asn1.dll</HintPath> <HintPath>packages\System.Formats.Asn1.8.0.2\lib\net462\System.Formats.Asn1.dll</HintPath>
@@ -98,6 +121,7 @@
<Reference Include="System.Threading.Tasks.Extensions, Version=4.2.4.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL"> <Reference Include="System.Threading.Tasks.Extensions, Version=4.2.4.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>packages\System.Threading.Tasks.Extensions.4.6.3\lib\net462\System.Threading.Tasks.Extensions.dll</HintPath> <HintPath>packages\System.Threading.Tasks.Extensions.4.6.3\lib\net462\System.Threading.Tasks.Extensions.dll</HintPath>
</Reference> </Reference>
<Reference Include="System.Web" />
<Reference Include="System.Xml.Linq" /> <Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" /> <Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" /> <Reference Include="Microsoft.CSharp" />
@@ -158,7 +182,11 @@
<DependentUpon>Resources.resx</DependentUpon> <DependentUpon>Resources.resx</DependentUpon>
<DesignTime>True</DesignTime> <DesignTime>True</DesignTime>
</Compile> </Compile>
<None Include="log4net.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Include="packages.config" /> <None Include="packages.config" />
<None Include="Properties\app.manifest" />
<None Include="Properties\DataSources\Profile.datasource" /> <None Include="Properties\DataSources\Profile.datasource" />
<None Include="Properties\DataSources\Program.datasource" /> <None Include="Properties\DataSources\Program.datasource" />
<None Include="Properties\Settings.settings"> <None Include="Properties\Settings.settings">
@@ -187,9 +215,7 @@
</BootstrapperPackage> </BootstrapperPackage>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<None Include="images.png" /> <None Include="SSH_Test_TemporaryKey.pfx" />
</ItemGroup>
<ItemGroup>
<None Include="unicorn.jpg" /> <None Include="unicorn.jpg" />
</ItemGroup> </ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />

View File

@@ -1,7 +1,7 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup> <PropertyGroup>
<PublishUrlHistory>publish\</PublishUrlHistory> <PublishUrlHistory>D:\Shared\VS\|publish\</PublishUrlHistory>
<InstallUrlHistory /> <InstallUrlHistory />
<SupportUrlHistory /> <SupportUrlHistory />
<UpdateUrlHistory /> <UpdateUrlHistory />
@@ -10,4 +10,7 @@
<FallbackCulture>en-US</FallbackCulture> <FallbackCulture>en-US</FallbackCulture>
<VerifyUploadedFiles>false</VerifyUploadedFiles> <VerifyUploadedFiles>false</VerifyUploadedFiles>
</PropertyGroup> </PropertyGroup>
<PropertyGroup>
<EnableSecurityDebugging>false</EnableSecurityDebugging>
</PropertyGroup>
</Project> </Project>

Binary file not shown.

View File

@@ -1,4 +1,6 @@
using Org.BouncyCastle.Cms; using log4net;
using log4net.Config;
using Org.BouncyCastle.Cms;
using Renci.SshNet; using Renci.SshNet;
using Renci.SshNet.Common; using Renci.SshNet.Common;
using System; using System;
@@ -10,6 +12,7 @@ using System.Drawing;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Linq.Expressions; using System.Linq.Expressions;
using System.Reflection;
using System.Text; using System.Text;
using System.Text.Json; using System.Text.Json;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
@@ -19,7 +22,6 @@ using System.Windows.Forms;
using System.Xml; using System.Xml;
using static System.Windows.Forms.VisualStyles.VisualStyleElement; using static System.Windows.Forms.VisualStyles.VisualStyleElement;
namespace SSH_Test namespace SSH_Test
{ {
@@ -28,37 +30,39 @@ namespace SSH_Test
{ {
public List<cTask> Tasks = new List<cTask>(); public List<cTask> Tasks = new List<cTask>();
public cConInfo conInfo = new cConInfo("","","","","","","","",""); public cConInfo conInfo = new cConInfo("","","","","","","","","",false);
private List<Profile> Profiles = new List<Profile>(); private List<Profile> Profiles = new List<Profile>();
private static readonly ILog log = LogManager.GetLogger(typeof(Program));
public TastList() public TastList()
{ {
var logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());
XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));
InitializeComponent(); InitializeComponent();
// For creating the default profile.json
//Profile profile = new Profile("SSH_Cisco_Tftp_Running", "SSH", new string[] { "copy run tftp://" });
//Profiles.Add(profile);
//profile = new Profile("SSH_Cisco_Tftp_Startup", "SSH", new string[] { "copy startup-config tftp://" });
//Profiles.Add(profile);
//profile = new Profile("SSH_Cisco_Tftp_Enable_Running", "SSH", new string[] { "enable","copy running-config tftp://" });
//Profiles.Add(profile);
//SaveProfile(Profiles, "profile.json");
//Load Profile list from "profile.json" //Load Profile list from "profile.json"
Profiles = LoadProfile("profile.json"); Profiles = LoadProfile("profile.json");
foreach (Profile p in Profiles) // Configure Profile list to dropdown menu
try
{ {
Console.WriteLine("Profile: {0}", p.ProfileName); foreach (Profile p in Profiles)
{
log.Info(string.Format("Profile: {0}", p.ProfileName));
}
var comboBoxColumn = (DataGridViewComboBoxColumn)dataGridViewTask.Columns[7];
comboBoxColumn.DataSource = Profiles; // Set the data source of the ComboBox column
comboBoxColumn.DisplayMember = "profileName"; // Displayed property name
comboBoxColumn.ValueMember = "profileName"; //The property name of the value
}
catch(Exception ex)
{
log.Error(ex.Message);
} }
var comboBoxColumn = (DataGridViewComboBoxColumn)dataGridViewTask.Columns[7];
comboBoxColumn.DataSource = Profiles; // Set the data source of the ComboBox column
comboBoxColumn.DisplayMember = "profileName"; // Displayed property name
comboBoxColumn.ValueMember = "profileName"; //The property name of the value
dataGridViewTask.Refresh(); dataGridViewTask.Refresh();
} }
@@ -98,36 +102,57 @@ namespace SSH_Test
hostInfo.device = currentTask.sTaskDevice.ToString(); hostInfo.device = currentTask.sTaskDevice.ToString();
// print out task // print out task
Console.WriteLine("Current task profile {0}:", hostInfo.device); log.Info(string.Format("Current task profile {0}:", hostInfo.device));
foreach (string c in profile.ProfileCommands) foreach (string c in profile.ProfileCommands)
Console.WriteLine(c); log.Info(c);
hostInfo.Commands = profile.ProfileCommands; hostInfo.Commands = profile.ProfileCommands;
switch (profile.ProfileType) switch (profile.ProfileType)
{ {
case "SSH": case "SSH":
Thread thread1 = new Thread(new ParameterizedThreadStart(fSSH)); try
hostInfo.TftpIP = conInfo.sTftpIP; {
hostInfo.SftpIP = conInfo.sTftpIP; Thread thread1 = new Thread(new ParameterizedThreadStart(fSSH));
hostInfo.SftpPassword = conInfo.sTftpPassword; hostInfo.TftpIP = conInfo.sTftpIP;
hostInfo.SftpUsername = conInfo.sTftpUsername; hostInfo.SftpIP = conInfo.sTftpIP;
thread1.Start(hostInfo); hostInfo.SftpPassword = conInfo.sTftpPassword;
hostInfo.SftpUsername = conInfo.sTftpUsername;
thread1.Start(hostInfo);
}
catch(Exception ex1)
{
log.Error(ex1);
}
break; break;
case "SSH_Catalyst": case "SSH_Catalyst":
Thread thread2 = new Thread(new ParameterizedThreadStart(fSSH_Catalyst)); try
hostInfo.TftpIP = conInfo.sTftpIP; {
hostInfo.SftpIP = conInfo.sTftpIP; Thread thread2 = new Thread(new ParameterizedThreadStart(fSSH_Catalyst));
hostInfo.SftpPassword = conInfo.sTftpPassword; hostInfo.TftpIP = conInfo.sTftpIP;
hostInfo.SftpUsername = conInfo.sTftpUsername; hostInfo.SftpIP = conInfo.sTftpIP;
thread2.Start(hostInfo); hostInfo.SftpPassword = conInfo.sTftpPassword;
hostInfo.SftpUsername = conInfo.sTftpUsername;
thread2.Start(hostInfo);
}
catch (Exception ex1)
{
log.Error(ex1);
}
break; break;
case "RAC9": case "RAC9":
string command = ""; string command = "";
command = " --nocertwarn -r " + conInfo.sIDracIP + " -u " + conInfo.sIDracUsername + " -p " + conInfo.sIDracPassword + " ";
if (!conInfo.bisLocal)
{
command = " --nocertwarn -r " + conInfo.sIDracIP + " -u " + conInfo.sIDracUsername + " -p " + conInfo.sIDracPassword + " ";
}
foreach (string c in profile.ProfileCommands) foreach (string c in profile.ProfileCommands)
{ {
@@ -146,18 +171,97 @@ namespace SSH_Test
process.StartInfo.Arguments = command + " " + c; process.StartInfo.Arguments = command + " " + c;
process.Start(); process.Start();
string result = process.StandardOutput.ReadToEnd(); string result = process.StandardOutput.ReadToEnd();
Console.WriteLine("From RAC9 {0}: {1}", currentTask.sTaskDevice.ToString(), result); log.Info(string.Format("From RAC9 {0}: {1}", currentTask.sTaskDevice.ToString(), result));
process.WaitForExit(); process.WaitForExit();
} }
catch (Win32Exception ex) catch (Win32Exception ex)
{ {
Console.WriteLine($"Error: {ex.Message}. The user likely declined the UAC prompt."); log.Info(string.Format($"Error: {ex.Message}. The user likely declined the UAC prompt."));
} }
} }
break; break;
case "CMD":
command = "/c";
foreach (string c in profile.ProfileCommands)
{
Process process = new Process();
process.StartInfo.FileName = "cmd.exe";
process.StartInfo.UseShellExecute = false; // Required for 'runas' verb
process.StartInfo.Verb = "runas"; // Request administrator privileges
process.StartInfo.WorkingDirectory = Environment.CurrentDirectory; // current working dir
process.StartInfo.RedirectStandardOutput = true;
try
{
string tempfile = DateTime.Now.ToString().Replace(":", "").Replace(" ", "") + ".txt";
process.StartInfo.Arguments = command + " " + c;
process.Start();
string result = process.StandardOutput.ReadToEnd();
log.Info(string.Format("From CMD {0}: {1}", currentTask.sTaskDevice.ToString(), result));
process.WaitForExit();
}
catch (Win32Exception ex)
{
log.Error(ex);
}
}
break;
case "Powershell":
command = " ";
foreach (string c in profile.ProfileCommands)
{
Process process = new Process();
process.StartInfo.FileName = "powershell";
process.StartInfo.UseShellExecute = false; // Required for 'runas' verb
process.StartInfo.Verb = "runas"; // Request administrator privileges
string folderPathPS = Environment.CurrentDirectory + "\\PS";
process.StartInfo.WorkingDirectory = folderPathPS; // current working dir
// check if Powershell Script folder "PS" exists, if not , create one.
if (!Directory.Exists(folderPathPS))
{
Directory.CreateDirectory(folderPathPS);
log.Info(string.Format("Cound not find folder PS, create new {0}", folderPathPS));
}
process.StartInfo.RedirectStandardOutput = true;
try
{
string tempfile = DateTime.Now.ToString().Replace(":", "").Replace(" ", "") + ".txt";
process.StartInfo.Arguments = command + " " + c;
process.Start();
string result = process.StandardOutput.ReadToEnd();
log.Info(string.Format("From Powershell {0}: {1}", currentTask.sTaskDevice.ToString(), result));
process.WaitForExit();
}
catch (Win32Exception ex)
{
log.Error(ex);
}
}
break;
default: default:
break; break;
@@ -220,15 +324,8 @@ namespace SSH_Test
} }
catch ( Exception ex) catch ( Exception ex)
{ {
log.Error(ex);
} }
} }
private void dataGridViewTask_CellEndEdit(object sender, DataGridViewCellEventArgs e) private void dataGridViewTask_CellEndEdit(object sender, DataGridViewCellEventArgs e)
@@ -261,7 +358,8 @@ namespace SSH_Test
break; break;
case 7: // Profile case 7: // Profile
Tasks[e.RowIndex].sProfile = (string)dataGridViewTask.Rows[e.RowIndex].Cells[e.ColumnIndex].Value; Tasks[e.RowIndex].sProfile = (string)dataGridViewTask.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
Console.WriteLine("Task {0}, profile {1}", e.RowIndex, Tasks[e.RowIndex].sProfile); log.Info(string.Format("Task {0}, profile {1}", e.RowIndex, Tasks[e.RowIndex].sProfile));
break; break;
default: default:
break; break;
@@ -275,7 +373,7 @@ namespace SSH_Test
{ {
using (Stream stream = File.Open("tasklist.dat", FileMode.Create)) using (Stream stream = File.Open("tasklist.dat", FileMode.Create))
{ {
Console.WriteLine("Saving Tasklist.dat"); log.Info("Saving Tasklist.dat");
var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
binaryFormatter.Serialize(stream, Tasks); binaryFormatter.Serialize(stream, Tasks);
} }
@@ -346,226 +444,253 @@ namespace SSH_Test
public void fSSH(object data) public void fSSH(object data)
{ {
cHostInfo hostinfo = (cHostInfo)data; try
string host = hostinfo.host;
string device = hostinfo.device;
string username = hostinfo.username;
string password = hostinfo.password;
string tftpIp = hostinfo.TftpIP;
string sftpIp = hostinfo.SftpIP;
string sftpUsername = hostinfo.SftpUsername;
string sftpPassword = hostinfo.SftpPassword;
string[] Commands = hostinfo.Commands;
var client = new SshClient(hostinfo.host, hostinfo.username, hostinfo.password);
Console.WriteLine("From fSSH {0}: Establishing a connection", device);
client.Connect();
Console.WriteLine(client.ConnectionInfo.ServerVersion);
if (client.IsConnected)
{ {
var shellStream = client.CreateShellStream("xterm", 80, 24, 800, 600, 1024); cHostInfo hostinfo = (cHostInfo)data;
var output = ""; string host = hostinfo.host;
var result = ""; string device = hostinfo.device;
string username = hostinfo.username;
string password = hostinfo.password;
string tftpIp = hostinfo.TftpIP;
string sftpIp = hostinfo.SftpIP;
string sftpUsername = hostinfo.SftpUsername;
string sftpPassword = hostinfo.SftpPassword;
string[] Commands = hostinfo.Commands;
var client = new SshClient(hostinfo.host, hostinfo.username, hostinfo.password);
log.Info(string.Format("From fSSH {0}: Establishing a connection", device));
//wait for "User Name:"
output = shellStream.Expect(new Regex(@"Name:|name:")); client.Connect();
Console.WriteLine("From fSSH {0}: {1}", device, output); log.Info(client.ConnectionInfo.ServerVersion);
//send username if (client.IsConnected)
shellStream.WriteLine(username);
//wait for "Password:"
output = shellStream.Expect(new Regex(@"word:"));
Console.WriteLine("From fSSH {0}: {1}", device, output);
//send password
shellStream.WriteLine(password);
//wait for "Prompt:"
output = shellStream.Expect(new Regex(@"#"));
Console.WriteLine("From fSSH {0}: {1}", device, output);
output = "";
//create filename
string datetime = DateTime.Now.ToString().Replace(":", "");
datetime = datetime.Replace(" ", "_");
// string filePath = string.Format("{0}_{1}.txt", currentTask.sTaskDevice, datetime.Replace("-", ""));
string filePath = string.Format("{0}_{1}.txt", device, datetime.Replace("-", ""));
foreach (string c in Commands)
{ {
switch (c) var shellStream = client.CreateShellStream("xterm", 80, 24, 800, 600, 1024);
var output = "";
var result = "";
//wait for "User Name:"
output = shellStream.Expect(new Regex(@"Name:|name:"));
log.Info(string.Format("From fSSH {0}: {1}", device, output));
//send username
shellStream.WriteLine(username);
//wait for "Password:"
output = shellStream.Expect(new Regex(@"word:"));
log.Info(string.Format("From fSSH {0}: {1}", device, output));
//send password
shellStream.WriteLine(password);
//wait for "Prompt:"
output = shellStream.Expect(new Regex(@"#"));
log.Info(string.Format("From fSSH {0}: {1}", device, output));
output = "";
//create filename
string datetime = DateTime.Now.ToString().Replace(":", "");
datetime = datetime.Replace(" ", "_");
// string filePath = string.Format("{0}_{1}.txt", currentTask.sTaskDevice, datetime.Replace("-", ""));
string filePath = string.Format("{0}_{1}.txt", device, datetime.Replace("-", ""));
foreach (string c in Commands)
{ {
//enable switch (c)
case "enable": {
output = ""; //enable
shellStream.WriteLine(c); case "enable":
//wait for "Password:" output = "";
output = shellStream.Expect(new Regex(@"word:")); shellStream.WriteLine(c);
Console.WriteLine("From fSSH {0}: {1}", device, c); //wait for "Password:"
output = shellStream.Expect(new Regex(@"word:"));
//send password log.Info(string.Format("From fSSH {0}: {1}", device, c));
shellStream.WriteLine(password);
break;
// tftp
case string s when Regex.IsMatch(c, @"tftp"):
output = "";
string command = string.Format("{0}{1}/{2}", c, tftpIp, filePath);
Console.WriteLine("From fSSH {0}: {1}", device, command);
//send tftp command
shellStream.WriteLine(command);
//wait "<return>" to send "space" and loop until get prompt //send password
while (!Regex.IsMatch(output, "#")) shellStream.WriteLine(password);
{ break;
output = shellStream.Expect(new Regex(@"More|<return>|#"));
shellStream.WriteLine(" "); // tftp
string[] lines = output.Split('\n'); case string s when Regex.IsMatch(c, @"tftp"):
var output1 = ""; output = "";
for (int ii = 0; ii < (lines.Length - 1); ii++) string command = string.Format("{0}{1}/{2}", c, tftpIp, filePath);
output1 += lines[ii]; log.Info(string.Format("From fSSH {0}: {1}", device, command));
Console.WriteLine(output1);
result += output1;
}
break;
default:
shellStream.WriteLine(c);
//wait for "Prompt:"
output = shellStream.Expect(new Regex(@"#"));
Console.WriteLine("From fSSH_Test {0}: {1}", device, output);
break;
//send tftp command
shellStream.WriteLine(command);
//wait "<return>" to send "space" and loop until get prompt
while (!Regex.IsMatch(output, "#"))
{
output = shellStream.Expect(new Regex(@"More|<return>|#"));
shellStream.WriteLine(" ");
string[] lines = output.Split('\n');
var output1 = "";
for (int ii = 0; ii < (lines.Length - 1); ii++)
output1 += lines[ii];
log.Info(output1);
result += output1;
}
break;
default:
shellStream.WriteLine(c);
//wait for "Prompt:"
output = shellStream.Expect(new Regex(@"#"));
log.Info(string.Format("From fSSH_Test {0}: {1}", device, output));
break;
}
} }
} }
client.Disconnect();
log.Info(string.Format("From SSH_Test: Disconnected"));
}
catch (Exception e)
{
log.Error("SSH function: cannot run SSH");
log.Error(e);
} }
client.Disconnect();
Console.WriteLine("From SSH_Test: Disconnected");
} }
public void fSSH_Catalyst(object data) public void fSSH_Catalyst(object data)
{ {
cHostInfo hostinfo = (cHostInfo)data; try
string host = hostinfo.host;
string device = hostinfo.device;
string username = hostinfo.username;
string password = hostinfo.password;
string tftpIp = hostinfo.TftpIP;
string sftpIp = hostinfo.SftpIP;
string sftpUsername = hostinfo.SftpUsername;
string sftpPassword = hostinfo.SftpPassword;
string[] Commands = hostinfo.Commands;
var client = new SshClient(hostinfo.host, hostinfo.username, hostinfo.password);
Console.WriteLine("From fSSH_Catalyst {0}: Establishing a connection", device);
client.Connect();
Console.WriteLine("From fSSH_Catalyst {0}: {1}", device, client.ConnectionInfo.ServerVersion);
if (client.IsConnected)
{ {
var shellStream = client.CreateShellStream("xterm", 80, 24, 800, 600, 1024); cHostInfo hostinfo = (cHostInfo)data;
var output = "";
var result = "";
var prompt = "";
//output = "";
output = shellStream.Expect(new Regex(@"#"));
Console.WriteLine("From fSSH_Catalyst {0}: {1}", device, output);
prompt = output;
shellStream.WriteLine(""); string host = hostinfo.host;
shellStream.Flush(); string device = hostinfo.device;
string username = hostinfo.username;
string password = hostinfo.password;
string tftpIp = hostinfo.TftpIP;
string sftpIp = hostinfo.SftpIP;
string sftpUsername = hostinfo.SftpUsername;
string sftpPassword = hostinfo.SftpPassword;
string[] Commands = hostinfo.Commands;
output = shellStream.Expect(new Regex(prompt)); var client = new SshClient(hostinfo.host, hostinfo.username, hostinfo.password);
Console.WriteLine("From fSSH_Catalyst {0}: {1}", device, output); log.Info(string.Format("From fSSH_Catalyst {0}: Establishing a connection {1}", device, host));
//create filename
string datetime = DateTime.Now.ToString().Replace(":", "");
datetime = datetime.Replace(" ", "_");
// string filePath = string.Format("{0}_{1}.txt", currentTask.sTaskDevice, datetime.Replace("-", ""));
string filePath = string.Format("{0}_{1}.txt", device, datetime.Replace("-", ""));
foreach (string c in Commands) client.Connect();
log.Info(string.Format("From fSSH_Catalyst {0}: {1}", device, client.ConnectionInfo.ServerVersion));
if (client.IsConnected)
{ {
switch (c) var shellStream = client.CreateShellStream("xterm", 80, 24, 800, 600, 1024);
var output = "";
var result = "";
var prompt = "";
//output = "";
output = shellStream.Expect(new Regex(@"#"));
log.Info(string.Format("From fSSH_Catalyst {0}: {1}", device, output));
prompt = output;
shellStream.WriteLine("");
shellStream.Flush();
output = shellStream.Expect(new Regex(prompt));
log.Info(string.Format("From fSSH_Catalyst {0}: {1}", device, output));
//create filename
string datetime = DateTime.Now.ToString().Replace(":", "");
datetime = datetime.Replace(" ", "_");
// string filePath = string.Format("{0}_{1}.txt", currentTask.sTaskDevice, datetime.Replace("-", ""));
string filePath = string.Format("{0}_{1}.txt", device, datetime.Replace("-", ""));
foreach (string c in Commands)
{ {
//enable switch (c)
case "enable": {
output = ""; //enable
shellStream.WriteLine(c); case "enable":
//wait for "Password:"
output = shellStream.Expect(new Regex(@"word:"));
Console.WriteLine("From fSSH_Catalyst {0}: {1}", device, c);
//send password
shellStream.WriteLine(password);
break;
// tftp
case string s when Regex.IsMatch(c, @"tftp"):
output = "";
string command = string.Format("{0}{1}/{2}", c, tftpIp, filePath);
Console.WriteLine("From fSSH_Catalyst {0}: {1}", device, command);
//send tftp command
output = "";
shellStream.WriteLine(command);
shellStream.Flush();
//handle shell interaction, wait for "?" then send "enter"
output = shellStream.Expect(new Regex(@"\?"));
Console.WriteLine("From fSSH{0}: {1}", device, output);
while (output.Contains("?"))
{
output = ""; output = "";
shellStream.WriteLine(""); shellStream.WriteLine(c);
//wait for "Password:"
output = shellStream.Expect(new Regex(@"word:"));
log.Info(string.Format("From fSSH_Catalyst {0}: {1}", device, c));
//send password
shellStream.WriteLine(password);
break;
// tftp
case string s when Regex.IsMatch(c, @"tftp"):
output = "";
string command = string.Format("{0}{1}/{2}", c, tftpIp, filePath);
log.Info(string.Format("From fSSH_Catalyst {0}: {1}", device, command));
//send tftp command
output = "";
shellStream.WriteLine(command);
shellStream.Flush(); shellStream.Flush();
output = shellStream.Expect(new Regex(@"\?|#"));
Console.WriteLine("From fSSH_Catalyst {0}: {1}", device, output);
}
break; //handle shell interaction, wait for "?" then send "enter"
default:
shellStream.WriteLine(c);
//wait for "Prompt:"
output = shellStream.Expect(prompt);
Console.WriteLine("From fSSH_Test {0}: {1}", device, output);
break;
output = shellStream.Expect(new Regex(@"\?"));
log.Info(string.Format("From fSSH_Catalyst{0}: {1}", device, output));
while (output.Contains("?"))
{
output = "";
shellStream.WriteLine("");
shellStream.Flush();
output = shellStream.Expect(new Regex(@"\?|#"));
log.Info(string.Format("From fSSH_Catalyst {0}: {1}", device, output));
}
break;
default:
shellStream.WriteLine(c);
//wait for "Prompt:"
output = shellStream.Expect(prompt);
log.Info(string.Format("From fSSH_Catalyst {0}: {1}", device, output));
break;
}
} }
} }
} client.Disconnect();
log.Info(string.Format("From SSH_Catalyst: Disconnected"));
client.Disconnect();
Console.WriteLine("From SSH_Test: Disconnected"); }
catch (Exception e)
{
log.Error("SSH_Catalyst function: cannot run SSH_Catalyst");
log.Error(e);
}
} }
private void buttonConf_Click(object sender, EventArgs e) private void buttonConf_Click(object sender, EventArgs e)
{ {
FormConfiguration formConfiguration = new FormConfiguration(conInfo.sTftpIP, conInfo.sSftpIP, conInfo.sSftpUsername, conInfo.sSftpPassword,conInfo.sIDracIP, conInfo.sIDracUsername, conInfo.sIDracPassword); FormConfiguration formConfiguration = new FormConfiguration(conInfo.sTftpIP, conInfo.sSftpIP, conInfo.sSftpUsername, conInfo.sSftpPassword,conInfo.sIDracIP, conInfo.sIDracUsername, conInfo.sIDracPassword, conInfo.bisLocal);
formConfiguration.ShowDialog(); formConfiguration.ShowDialog();
conInfo.sTftpIP = formConfiguration.Tftp_IP; conInfo.sTftpIP = formConfiguration.Tftp_IP;
conInfo.sSftpIP = formConfiguration.Sftp_IP; conInfo.sSftpIP = formConfiguration.Sftp_IP;
@@ -574,6 +699,7 @@ namespace SSH_Test
conInfo.sIDracIP = formConfiguration.IDRAC_IP; conInfo.sIDracIP = formConfiguration.IDRAC_IP;
conInfo.sIDracUsername = formConfiguration.IDRAC_Username; conInfo.sIDracUsername = formConfiguration.IDRAC_Username;
conInfo.sIDracPassword = formConfiguration.IDRAC_Password; conInfo.sIDracPassword = formConfiguration.IDRAC_Password;
conInfo.bisLocal = formConfiguration.IDRAC_Local;
} }
//Seriallize Profile to a Json file //Seriallize Profile to a Json file
@@ -589,10 +715,26 @@ namespace SSH_Test
//Deseriallize Profile from a Json file //Deseriallize Profile from a Json file
private static List<Profile> LoadProfile(string filePath) private static List<Profile> LoadProfile(string filePath)
{ {
if (File.Exists(filePath)) if (File.Exists(filePath))
{ {
string jsonString = File.ReadAllText(filePath); try
return JsonSerializer.Deserialize<List<Profile>>(jsonString); {
string jsonString = File.ReadAllText(filePath);
return JsonSerializer.Deserialize<List<Profile>>(jsonString);
}
catch (Exception ex)
{
//could not read profile.json properly
log.Error("Could not load profile.json");
log.Error(ex);
//return an empty list if file could not be read
return new List<Profile>();
}
} }
return new List<Profile>(); // Return an empty list if file doesn't exist return new List<Profile>(); // Return an empty list if file doesn't exist
} }
@@ -634,8 +776,8 @@ namespace SSH_Test
public string sIDracIP { get; set; } public string sIDracIP { get; set; }
public string sIDracUsername { get; set; } public string sIDracUsername { get; set; }
public string sIDracPassword { get; set; } public string sIDracPassword { get; set; }
public bool bisLocal { get; set; }
public cConInfo( string TftpIP, string TftpUsername, string TftpPassword, string SftpIP, String SftpUsername, String SftPassword, String IdracIP, String IdracUsername, String IdracPassword) public cConInfo( string TftpIP, string TftpUsername, string TftpPassword, string SftpIP, String SftpUsername, String SftPassword, String IdracIP, String IdracUsername, String IdracPassword, bool IsLocal)
{ {
this.sTftpIP = TftpIP; this.sTftpIP = TftpIP;
this.sTftpUsername = TftpUsername; this.sTftpUsername = TftpUsername;
@@ -646,6 +788,7 @@ namespace SSH_Test
this.sIDracIP = IdracIP; this.sIDracIP = IdracIP;
this.sIDracUsername = IdracUsername; this.sIDracUsername = IdracUsername;
this.sIDracPassword = IdracPassword; this.sIDracPassword = IdracPassword;
this.bisLocal = IsLocal;
} }
} }