Erstmal ein Hallo ans Forum.
Ich bin gelernter Fachinformatiker Systemintegration und daher ist mein Wissen bezüglich C# echt bescheiden.
3Tage habe ich mich jetzt mit meinen Prog beschäftigt, jedoch komme ich nicht auf die notwendigen Lösungen.
Ziel:
+bestimmte Prozesse als Dienst umsetzen
+ohne Fenster
+Befehleingabe an den Prozess ermöglichen
+Ausgabe des Prozesses in Logfile
Unten habe ich mal angehängt was ich bisher programmiert habe.
Mein erstes Hauptproblem ist zum Bsp. dass ich Tools wie nslookup etc. beendet bekomme, aber die nötigen Prozesse oder zum bsp. das Tool portping (http://thommy88.th.funpic.de/portping-verwendung-13-35.html) nicht. Ich bekomme kein Strg+C zur Anwendung durch. Auch bekomme ich den Output der nötigen Prozesse nicht abgefragt. (Nslookup etc. funktioniert aber)
Das sind eigentlich meine Hauptprobleme.
Meine Logik ist folgende, da ich eine nötige offene Session komplett unterbinden möchte:
Ich möchte das die Befehle für die Anwendung und den Dienst, aus einem Textfile (input.txt wird beim Start angelegt) gelesen wird. (das klappt auch, zum bsp. wenn die Anwendung Nslookup ist, aber nicht bei meinen gewünschten prozessen)
Dieses Vorgehen würde mir später eine Eingabe über ein weiteres Tool ermöglichen.
Es soll die Anwendung als Dienst laufen, ohne dass eine RDP Session benötigt wird oder die Anwendung in einem Fenster abläuft. Daher kann ich mir wmclose() mir abschmieren.
Habt ihr eine Idee, wie ich die Ziele umsetzen kann?
Also Standardoutput bringt mir leider bei den Prozessen keine Rückantwort, auch tools wie firedaemon bringt da nix.
Mfg. Chris
ps.der code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
namespace ConsoleApplication1
{
public class MyVars
{
public string inifile;
[DllImport("kernel32")]
public static extern int GetPrivateProfileString(string section,
string key, string def, StringBuilder retVal, int size, string filePath);
public static string GetString(string section, string key)
{ string inifile = Environment.CurrentDirectory + "\\settings.INI";
StringBuilder temp = new StringBuilder(255);
int i = GetPrivateProfileString(section, key, "", temp, 255, inifile);
return temp.ToString(); }
[DllImport("kernel32.dll")]
public static extern Boolean SetConsoleCtrlHandler(HandlerRoutine Handler,
Boolean Add);
public delegate Boolean HandlerRoutine(CtrlTypes CtrlType);
public enum CtrlTypes
{
CTRL_C_EVENT = 0,
CTRL_BREAK_EVENT,
CTRL_CLOSE_EVENT,
CTRL_LOGOFF_EVENT = 5,
CTRL_SHUTDOWN_EVENT
}
[DllImport("kernel32.dll")]
public static extern bool GenerateConsoleCtrlEvent(ConsoleCtrlEvent sigevent, int dwProcessGroupId);
public enum ConsoleCtrlEvent
{
CTRL_C = 0,
CTRL_BREAK = 1,
CTRL_CLOSE = 2,
CTRL_LOGOFF = 5,
CTRL_SHUTDOWN = 6
}
public static volatile bool SENDING_CTRL_C_TO_CHILD = false;
public static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
e.Cancel = SENDING_CTRL_C_TO_CHILD;
}
}
class program
{
public static int countgetinput;
public static int countwhile = 0;
public static string returned1;
private static StreamReader file = null;
private static StreamWriter log = null;
private static FileInfo ifile = null;
private static Process myProc = null;
private static FileInfo ilogfile = null;
private static FileStream fs = null;
private static string Logfolder = "C:\\output\\Portping\\logs";
private static string stdLogfile = Logfolder + "\\log.txt";
private static string AppWorkingDir = "C:\\output\\PortPing";
private static string App = "C:\\output\\PortPing\\PortPing.exe";
private static string AppArg = "127.0.0.1 3389";
// private static string AppWorkingDir = “C:\output”;
// private static string App = “nslookup”;
private static string Inputfile = AppWorkingDir + “\input.txt”;
private static int logsizeinhours = 3;
public static void myProc_ErrorDataReceived(object sender, DataReceivedEventArgs e)
{
Console.WriteLine(e.Data);
}
public static void myProc_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
Console.WriteLine(e.Data);
if (ilogfile == null)
{ilogfile = new FileInfo(stdLogfile);
}
if (!File.Exists(stdLogfile))
{
fs = ilogfile.Open(FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
fs.Close();
}
fs = ilogfile.Open(FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
log = new StreamWriter(fs);
log.WriteLine(e.Data);
log.Close();
fs.Close();
string datum = DateTime.Now.Day + "_" + DateTime.Now.Month + "_" + DateTime.Now.Year;
string filedate = DateTime.Now.Day + "_" + DateTime.Now.Hour + "_" + DateTime.Now.Minute + "_" + DateTime.Now.Second;
if (ilogfile.CreationTime < DateTime.Now.AddHours(-logsizeinhours))
{if (!File.Exists(Logfolder + "\\" + filedate + ".txt"))
{
if (File.Exists(stdLogfile))
{
ilogfile.CreationTime = DateTime.Now;
System.IO.File.Move(stdLogfile, Logfolder + "\\" + filedate + ".txt");
}
}
}
}
public static string readcommands(int counter)
{
string line = "";
if (File.Exists(Inputfile))
{
try
{
if (file != null)
{
file.Close();
}
System.Threading.Thread.Sleep(1000);
//
ifile = new FileInfo(Inputfile);
FileStream fs = ifile.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
file = new StreamReader(fs);
while (counter.Equals(0))
{
line = file.ReadLine();
counter++;
}
file.Close();
fs.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
Console.WriteLine("Exception");
}
}
else
{
try
{
FileInfo wfi = new FileInfo(Inputfile);
FileStream fs = wfi.Create();
fs.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
return line;
}
public static void Main()
{
if (File.Exists(Inputfile))
{ System.IO.File.Delete(Inputfile); }
Console.CancelKeyPress += new ConsoleCancelEventHandler(MyVars.Console_CancelKeyPress);
/*
ConsoleKeyInfo test;
Console.WriteLine(ConsoleModifiers.Control + " " + ConsoleKey.C);
test= Console.ReadKey();
Console.WriteLine(ConsoleKey.A);
Console.WriteLine("start" + Convert.ToString(test));
*/
if (File.Exists(Environment.CurrentDirectory + "\\settings.INI")) {
readconfigfile();
}
Console.WriteLine("readconfigfile from" + Environment.CurrentDirectory + "\\settings.INI done");
startprog();
}
//start programm
public static void startprog()
{
Console.WriteLine(Logfolder);
Console.WriteLine(AppWorkingDir);
Console.WriteLine(stdLogfile);
Console.WriteLine(App);
Console.WriteLine(AppArg);
Console.WriteLine(Inputfile);
Console.WriteLine(logsizeinhours);
string command = "";
Console.WriteLine("process creation");
ProcessStartInfo P = new ProcessStartInfo();
Console.WriteLine("set filename");
P.FileName = App;
P.Arguments = AppArg;
Console.WriteLine("create logfolder");
if (!Directory.Exists(Logfolder)) {Directory.CreateDirectory(Logfolder); }
Console.WriteLine("create appfolder");
if (!Directory.Exists(AppWorkingDir)) {Directory.CreateDirectory(AppWorkingDir); }
Console.WriteLine("set appfolder");
P.WorkingDirectory = AppWorkingDir;
P.UseShellExecute = false;
Console.WriteLine("set redirects for process");
P.RedirectStandardOutput = true;
P.RedirectStandardInput = true;
P.RedirectStandardError = true;
Console.WriteLine("start process");
Process myProc = Process.Start(P);
Console.WriteLine(myProc.ProcessName + " " + myProc.Id);
Console.WriteLine("Begin Outputread");
myProc.BeginOutputReadLine();
Console.WriteLine("EventHandler for data output");
myProc.OutputDataReceived += new DataReceivedEventHandler(myProc_OutputDataReceived);
myProc.ErrorDataReceived += new DataReceivedEventHandler(myProc_ErrorDataReceived);
Console.WriteLine("start while");
while (command != "exit")
{ countwhile++;
Console.WriteLine(myProc.StandardError);
command = getinput(1);
myProc.StandardInput.WriteLine(command);
if (command == "exit") {
Console.WriteLine(command);
Console.WriteLine("{0} is active: {1}", myProc.Id, !myProc.HasExited);
MyVars.SENDING_CTRL_C_TO_CHILD = true;
Console.WriteLine(MyVars.GenerateConsoleCtrlEvent(MyVars.ConsoleCtrlEvent.CTRL_C, myProc.Id));
Console.WriteLine(MyVars.GenerateConsoleCtrlEvent(MyVars.ConsoleCtrlEvent.CTRL_C, myProc.Id));
myProc.StandardInput.WriteLine("\x3");
Console.WriteLine("{0} is active: {1}", myProc.Id, !myProc.HasExited);
myProc.StandardInput.WriteLine("\x03");
Console.WriteLine("{0} is active: {1}", myProc.Id, !myProc.HasExited);
myProc.StandardInput.WriteLine("\0x03");
Console.WriteLine("{0} is active: {1}", myProc.Id, !myProc.HasExited);
myProc.StandardInput.WriteLine(0x03);
Console.WriteLine("{0} is active: {1}", myProc.Id, !myProc.HasExited);
Console.WriteLine("\x3");
Console.WriteLine("{0} is active: {1}", myProc.Id, !myProc.HasExited);
Console.WriteLine("\x03");
Console.WriteLine("{0} is active: {1}", myProc.Id, !myProc.HasExited);
Console.WriteLine("\0x03");
Console.WriteLine("{0} is active: {1}", myProc.Id, !myProc.HasExited);
Console.WriteLine("^C");
myProc.CloseMainWindow();
Console.WriteLine(0x03);
Console.WriteLine("{0} is active: {1}", myProc.Id, !myProc.HasExited);
Console.WriteLine("PID:" + myProc.Id);
//Console.WriteLine((getprog("MasterServer"))+" " + MyVars.GenerateConsoleCtrlEvent(MyVars.ConsoleCtrlEvent.CTRL_C, getprog("MasterServer")));
MyVars.SENDING_CTRL_C_TO_CHILD = false;
System.Threading.Thread.Sleep(5000);
Console.WriteLine("{0} is active: {1}", myProc.Id, !myProc.HasExited);
// myProc.WaitForExit();
myProc.StandardInput.Close();
myProc.Close();
}
}
}
public static int getprog(string procsearch)
{
string procid;
string procname;
string procpathfile;
int procreturn;
procreturn=999;
procid = "";
Process[] pp = Process.GetProcesses();
foreach (Process p in pp)
{
procname = Convert.ToString(p.ProcessName);
if (procname.Equals(procsearch))
{
procid = Convert.ToString(p.Id);
procreturn = p.Id;
procpathfile = Convert.ToString(p.MainModule.FileName);
Console.WriteLine("Process ID = " + procid + " Processname: " + procname + " Abbildname = " + procpathfile);
//p.Kill();
p.CloseMainWindow();
}
}
return procreturn;
}
//getinput
public static string getinput(int countgetintput)
{
returned1 = null;
do
{ returned1 = readcommands(0);
if ((returned1 != "") && (returned1 != null)) { countgetinput = -1; }
countgetinput = countgetinput + 1;
} while (countgetinput !=0 );
try
{
if (returned1 != null)
{
System.IO.File.Delete(Inputfile);
}
}
catch (Exception)
{ }
return returned1;
}
static int readconfigfile()
{
Logfolder = MyVars.GetString("Option", "Logfolder");
stdLogfile = Logfolder + MyVars.GetString("Option", "stdLogfile");
AppWorkingDir = MyVars.GetString("Option", "AppWorkingDir");
App = MyVars.GetString("Option", "App");
Inputfile = AppWorkingDir + MyVars.GetString("Option", "Inputfile");
AppArg = MyVars.GetString("Option", "AppArg");
logsizeinhours = Convert.ToInt32(MyVars.GetString("Option", "logsizeinhours"));
return 0;
}
//close Programm wird nicht genutzt
/* public static void closeprog()
{
string procid;
string procname;
string procpathfile;
string procsearch;
procsearch = “AdobeARM”;
Process[] pp = Process.GetProcesses();
foreach (Process p in pp)
{
procname = Convert.ToString(p.ProcessName);
if (procname.Equals(procsearch))
{
procid = Convert.ToString(p.Id);
procpathfile = Convert.ToString(p.MainModule.FileName);
Console.WriteLine("Process ID = " + procid + " Processname: " + procname + " Abbildname = " + procpathfile);
//p.Kill();
}
}
}
*/
}
}